Python可视化数据分析-饼状图

一、前言

饼状图(Pie Chart)是一种常用的数据可视化图表,用于展示数据中各部分的占比关系。Python 中有多种库可以用于绘制饼状图,比较常用的包括 matplotlibpyecharts 和**plotly** 等。

二、使用 matplotlib 绘制饼状图
python 复制代码
import matplotlib.pyplot as plt

# 数据
labels = ['Apples', 'Oranges', 'Bananas', 'Grapes']
sizes = [30, 25, 20, 25]  # 每部分的占比
colors = ['gold', 'orange', 'lightgreen', 'lightcoral']  # 颜色
explode = (0.1, 0, 0, 0)  # 突出显示第一部分

# 绘制饼状图
plt.figure(figsize=(8, 6))
plt.pie(sizes, explode=explode, labels=labels, colors=colors,
        autopct='%1.1f%%', shadow=True, startangle=140)
plt.title('Fruit Distribution')  # 图表标题
plt.axis('equal')  # 使饼状图长宽相等
plt.show()

说明:

1)labels 是各部分的标签。

2)sizes 是各部分的大小(占比)。

3)colors 是各部分的颜色。

4)explode 是用于突出显示某部分的偏移量,0 表示不突出

效果图 :

三、使用 plotly 绘制饼状图
python 复制代码
import plotly.express as px

# 数据
labels = ['Apples', 'Oranges', 'Bananas', 'Grapes']
sizes = [30, 25, 20, 25]  # 每部分的占比

# 创建图表
fig = px.pie(values=sizes, names=labels, title='Fruit Distribution')

# 显示图表
fig.show()

说明:

1)labels 是各部分的标签。

2)sizes 是各部分的大小(占比)。

  1. 使用 plotly.expresspx.pie 函数创建饼状图。

4)fig.show() 方法用于显示图表。

效果图:

四、使用 pyecharts 生成饼状图
python 复制代码
from pyecharts import options as opts
from pyecharts.charts import Pie

# 数据
labels = ['Apples', 'Oranges', 'Bananas', 'Grapes']
sizes = [30, 25, 20, 25]  # 每部分的占比

# 创建饼状图对象
pie_chart = Pie()

# 添加数据和配置
pie_chart.add("", [list(z) for z in zip(labels, sizes)], radius=["30%", "75%"])

# 设置全局配置
pie_chart.set_global_opts(title_opts=opts.TitleOpts(title="Fruit Distribution"))

# 显示图表(生成 HTML 文件)
pie_chart.render("pie_chart.html")

上述代码中使用了 pyecharts 库的 Pie 类来创建饼状图。我们可以通过添加数据和配置来自定义饼状图的样式和布局。最后,调用 render 方法将图表生成为 HTML 文件并显示出来。

效果图:

相关推荐
费弗里11 分钟前
Python全栈应用开发利器Dash 3.x新版本介绍(1)
python·dash
李少兄9 天前
解决OSS存储桶未创建导致的XML错误
xml·开发语言·python
就叫飞六吧9 天前
基于keepalived、vip实现高可用nginx (centos)
python·nginx·centos
Vertira9 天前
PyTorch中的permute, transpose, view, reshape和flatten函数详解(已解决)
人工智能·pytorch·python
学Linux的语莫9 天前
python基础语法
开发语言·python
匿名的魔术师9 天前
实验问题记录:PyTorch Tensor 也会出现 a = b 赋值后,修改 a 会影响 b 的情况
人工智能·pytorch·python
Ven%9 天前
PyTorch 张量(Tensors)全面指南:从基础到实战
人工智能·pytorch·python
mahuifa9 天前
PySide环境配置及工具使用
python·qt·环境配置·开发经验·pyside
大熊猫侯佩9 天前
ruby、Python 以及 Swift 语言关于 “Finally” 实现的趣谈
python·ruby·swift
19899 天前
【Dify精讲】第19章:开源贡献指南
运维·人工智能·python·架构·flask·开源·devops