Python读取Excel绘制饼图
使用 Python 的 pyecharts、matplotlib 和 seaborn 三个库从 Excel 中读取数据并绘制饼图。每个库的代码示例均包含核心类、函数和属性的详细说明。
1. 使用 pyecharts 绘制饼图
pyecharts 是交互式可视化库,适合生成动态网页图表,饼图支持丰富的交互功能。
代码示例:
import pandas as pd
from pyecharts.charts import Pie
from pyecharts import options as opts
# 读取Excel数据
df = pd.read_excel("data.xlsx")
categories = df["类别"].tolist() # 类别名称列
values = df["占比"].tolist() # 数值列(如百分比或绝对数值)
# 将数据格式化为 (类别, 数值) 的列表
data_pairs = list(zip(categories, values))
# 创建饼图对象
pie = Pie()
# 添加数据并配置
pie.add(
series_name="占比分布", # 系列名称
data_pair=data_pairs, # 数据格式
radius=["30%", "70%"], # 内外半径(控制饼图大小)
rosetype="radius", # 玫瑰图模式("radius"按角度,"area"按面积)
label_opts=opts.LabelOpts(
formatter="{b}: {d}%", # 标签格式:类别 + 百分比
position="outside" # 标签位置(inside/outside)
)
)
# 配置全局选项
pie.set_global_opts(
title_opts=opts.TitleOpts(title="类别占比饼图"),
legend_opts=opts.LegendOpts(
orient="vertical", # 图例垂直排列
pos_left="left" # 图例位置靠左
)
)
# 渲染为HTML文件
pie.render("pyecharts_pie.html")
核心类与参数:
Pie(): 饼图对象,属于pyecharts.charts.Pie类。add(series_name, data_pair): 添加数据。radius: 控制饼图内外半径(如["30%", "70%"]表示空心圆环)。rosetype: 玫瑰图模式("radius"扇区角度不同,"area"扇区面积不同)。label_opts: 标签配置(formatter自定义显示格式)。
set_global_opts(): 配置标题和图例位置。
2. 使用 matplotlib 绘制饼图
matplotlib 是基础绘图库,适合生成高度定制的静态饼图。
代码示例:
import pandas as pd
import matplotlib.pyplot as plt
# 读取Excel数据
df = pd.read_excel("data.xlsx")
categories = df["类别"]
values = df["占比"]
# 创建画布和坐标系
fig, ax = plt.subplots(figsize=(8, 8))
# 绘制饼图
wedges, texts, autotexts = ax.pie(
values,
labels=categories,
autopct="%1.1f%%", # 显示百分比(保留1位小数)
startangle=90, # 起始角度(12点钟方向为0度)
colors=plt.cm.Pastel1.colors, # 颜色主题
explode=(0.1, 0, 0, 0), # 突出显示第一块
shadow=True, # 添加阴影
textprops={"fontsize": 12} # 文本属性
)
# 配置标题和图例
ax.set_title("类别占比饼图", fontsize=14)
ax.legend(
wedges,
categories,
title="类别",
loc="center left",
bbox_to_anchor=(1, 0.5) # 图例放在右侧
)
# 调整标签间距
plt.tight_layout()
plt.savefig("matplotlib_pie.png")
plt.show()
核心函数与参数:
ax.pie(): 绘制饼图的核心函数。autopct: 百分比显示格式(如"%1.1f%%")。startangle: 起始角度(默认从正东方向开始,设为90则从正北开始)。explode: 突出某一块(如(0.1, 0, 0, 0)表示第一个扇区外扩)。shadow: 是否添加阴影。textprops: 控制标签字体大小和颜色。
ax.legend(): 配置图例位置和标题。
3. 使用 seaborn 绘制饼图
seaborn 没有直接绘制饼图的函数,但可通过 matplotlib 结合 seaborn 主题快速生成美观的饼图。
代码示例:
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
# 读取Excel数据
df = pd.read_excel("data.xlsx")
categories = df["类别"]
values = df["占比"]
# 设置seaborn主题
sns.set_theme(style="whitegrid", font="SimHei") # 设置主题和字体
# 创建画布
plt.figure(figsize=(8, 8))
# 使用matplotlib绘制饼图(应用seaborn主题)
wedges, texts, autotexts = plt.pie(
values,
labels=categories,
autopct="%1.1f%%",
startangle=90,
colors=sns.color_palette("pastel"), # seaborn颜色调色板
wedgeprops={"edgecolor": "black", "linewidth": 0.5} # 边框样式
)
# 配置标题和图例
plt.title("类别占比饼图(Seaborn风格)", fontsize=14)
plt.legend(
wedges,
categories,
title="类别",
loc="center left",
bbox_to_anchor=(1, 0.5)
)
# 调整布局
plt.tight_layout()
plt.savefig("seaborn_pie.png")
plt.show()
核心函数与参数:
sns.set_theme(): 设置主题样式(如"whitegrid"、"darkgrid")。sns.color_palette(): 使用 seaborn 的颜色调色板(如"pastel"、"bright")。wedgeprops: 控制饼图扇区的边框样式(颜色、线宽)。
对比总结
| 库 | 特点 | 适用场景 |
|---|---|---|
pyecharts |
交互式图表,支持动态展示和网页嵌入 | 需要交互性或网页展示 |
matplotlib |
高度可定制化,支持复杂样式调整 | 学术论文、高精度静态图表 |
seaborn |
结合 matplotlib,默认样式美观 |
快速生成简洁美观的图表 |
注意事项
- 数据格式:确保数值列是纯数字(非字符串),总和不超过 100%(若为百分比)。
- 标签重叠:若类别过多,调整
label_opts或autopct的显示方式,或增大画布尺寸。 - 颜色映射:使用预定义颜色主题(如
plt.cm.Pastel1或sns.color_palette("pastel"))增强可读性。
浙公网安备 33010602011771号