Matplotlib 饼图(Pie)完全指南
饼图是 占比、构成、比例 可视化的经典工具。本教程带你从入门到 发表级,掌握 基础饼图、环形图、嵌套饼图、自动百分比、突出显示、艺术风格、动态标注、交互式、多图组合 等全部技巧。
一、基本饼图
import matplotlib.pyplot as plt
labels = ['苹果', '香蕉', '橙子', '葡萄']
sizes = [30, 25, 25, 20]
plt.pie(sizes, labels=labels)
plt.show()
二、核心参数详解
plt.pie(sizes,
labels=labels,
autopct='%1.1f%%', # 自动显示百分比
startangle=90, # 起始角度(12点钟方向)
counterclock=False, # 顺时针排列
colors=None, # 自定义颜色
wedgeprops=None, # 扇形边框样式
textprops=None, # 文字样式
explode=None) # 突出显示
三、自动显示百分比
plt.pie(sizes, labels=labels, autopct='%1.1f%%', startangle=90)
plt.axis('equal') # 确保饼图为正圆
plt.show()
autopct格式:
'%1.1f%%'→ 85.7%'%d%%'→ 86%lambda x: f'{x:.1f}%'→ 自定义
四、突出显示(Explode)
explode = [0.1, 0, 0, 0] # 第一个扇形突出 0.1
plt.pie(sizes, labels=labels, autopct='%1.1f%%',
explode=explode, startangle=90, shadow=True)
plt.axis('equal')
plt.show()
五、自定义颜色
colors = ['#ff9999', '#66b3ff', '#99ff99', '#ffcc99']
plt.pie(sizes, labels=labels, colors=colors, autopct='%1.1f%%', startangle=90)
plt.axis('equal')
plt.show()
渐变色(推荐)
from matplotlib.cm import get_cmap
cmap = get_cmap('Pastel1')
colors = cmap(np.linspace(0, 1, len(sizes)))
plt.pie(sizes, labels=labels, colors=colors, autopct='%1.1f%%', startangle=90)
六、环形图(Donut Chart)
plt.pie(sizes, labels=labels, autopct='%1.1f%%', startangle=90,
wedgeprops=dict(width=0.4, edgecolor='white')) # width 控制环宽
plt.axis('equal')
plt.show()
wedgeprops={'width': 0.3~0.5}越小越厚
七、嵌套饼图(Nested Pie)
# 外层:大类
outer_sizes = [40, 30, 30]
outer_labels = ['水果', '蔬菜', '肉类']
# 内层:子类
inner_sizes = [15, 25, 20, 10, 20, 10]
inner_labels = ['苹果', '香蕉', '胡萝卜', '西兰花', '鸡肉', '牛肉']
inner_colors = ['#ff6666', '#ffcc99', '#99ff99', '#66b3ff', '#c2c2f0', '#ffb3e6']
fig, ax = plt.subplots()
# 外层
ax.pie(outer_sizes, radius=1.3, labels=outer_labels,
wedgeprops=dict(width=0.3, edgecolor='white'),
startangle=90, colors=['#ff9999', '#66b3ff', '#99ff99'])
# 内层
ax.pie(inner_sizes, radius=1.0, labels=inner_labels,
labeldistance=0.7, colors=inner_colors,
wedgeprops=dict(width=0.4, edgecolor='white'),
startangle=90, textprops=dict(color='black', fontsize=10))
plt.axis('equal')
plt.title('嵌套饼图:食品构成')
plt.show()
八、图例分离(推荐用于标签过多)
plt.pie(sizes, autopct='%1.1f%%', startangle=90)
plt.legend(labels, loc='upper right', bbox_to_anchor=(1.3, 1))
plt.axis('equal')
plt.show()
九、文字样式控制
plt.pie(sizes, labels=labels, autopct='%1.1f%%', startangle=90,
textprops={'fontsize': 12, 'fontweight': 'bold', 'color': 'darkblue'})
十、完整专业示例(论文级)
import matplotlib.pyplot as plt
import numpy as np
plt.style.use('seaborn-v0_8')
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
# 数据
categories = ['研发', '市场', '运营', '行政', '其他']
values = [35, 25, 20, 15, 5]
colors = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd']
explode = [0.05, 0, 0, 0, 0]
fig, ax = plt.subplots(figsize=(10, 8))
# 绘制饼图
wedges, texts, autotexts = ax.pie(values,
labels=categories,
autopct=lambda pct: f'{pct:.1f}%\n({pct*sum(values)/100:.0f}万)',
startangle=90,
colors=colors,
explode=explode,
wedgeprops=dict(width=0.5, edgecolor='white', linewidth=2),
textprops=dict(fontsize=11),
pctdistance=0.75)
# 美化百分比文字
for autotext in autotexts:
autotext.set_color('white')
autotext.set_fontweight('bold')
autotext.set_fontsize(10)
# 添加图例
ax.legend(wedges, [f'{cat}: {val}万' for cat, val in zip(categories, values)],
title='部门预算', loc='center left', bbox_to_anchor=(1, 0, 0.5, 1), fontsize=11)
# 标题
ax.set_title('2025年公司预算分配\n(环形图展示)', fontsize=18, fontweight='bold', pad=30)
# 确保正圆
plt.axis('equal')
plt.tight_layout()
plt.savefig('pie_pro.png', dpi=300, bbox_inches='tight', facecolor='white')
plt.show()
十一、饼图速查表(收藏用)
# 基础
plt.pie(sizes, labels=labels, autopct='%1.1f%%')
plt.axis('equal')
# 突出
explode = [0.1, 0, 0, 0]
plt.pie(sizes, explode=explode)
# 环形图
plt.pie(sizes, wedgeprops=dict(width=0.4))
# 自定义百分比
autopct = lambda x: f'{x:.1f}%' if x > 5 else ''
# 图例分离
plt.legend(labels, loc='upper right', bbox_to_anchor=(1.3,1))
# 嵌套饼图
ax.pie(outer, radius=1.3, wedgeprops=dict(width=0.3))
ax.pie(inner, radius=1.0, wedgeprops=dict(width=0.4))
十二、常见问题解决
| 问题 | 解决方案 |
|---|---|
| 饼图不是正圆 | plt.axis('equal') |
| 标签重叠 | 用 legend 分离,或 autopct='' |
| 百分比太小看不清 | pctdistance=0.6,textprops={'color':'white'} |
| 颜色单调 | 使用 cmap='Set3' 或自定义 |
| 保存裁剪图例 | plt.savefig(..., bbox_inches='tight') |
十三、推荐风格模板
| 场景 | 推荐设置 |
|---|---|
| 论文 | 环形图 + 图例分离 + 白底 |
| PPT | 实心饼 + 突出 + 阴影 |
| 仪表盘 | 环形图 + 中心文字 |
| 占比对比 | 多子图饼图 |
十四、中心添加文字(仪表盘风格)
plt.pie(sizes, labels=labels, autopct='%1.1f%%', startangle=90,
wedgeprops=dict(width=0.4), colors=colors)
plt.text(0, 0, '总计\n100万', ha='center', va='center',
fontsize=14, fontweight='bold')
plt.axis('equal')
plt.show()
官方文档
- Pie API:https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.pie.html
- 示例图库:https://matplotlib.org/stable/gallery/pie_and_polar_charts/pie_features.html
总结:三步打造专业饼图
# 1. 数据 + 样式
wedges, texts, autotexts = plt.pie(sizes, labels=labels, autopct='%1.1f%',
colors=colors, explode=explode, startangle=90)
# 2. 美化文字
for autotext in autotexts:
autotext.set_color('white').set_fontweight('bold')
# 3. 输出
plt.axis('equal')
plt.legend(loc='upper right')
plt.savefig('pie.png', dpi=300, bbox_inches='tight')
一键生成环形图:
plt.pie([30,25,25,20], labels=['A','B','C','D'], autopct='%1.1f%%',
wedgeprops=dict(width=0.4, edgecolor='white'), startangle=90)
plt.axis('equal')
plt.show()
需要我为你:
- 生成 8种经典饼图模板?
- 制作 Jupyter 饼图交互小工具(滑块调整占比)?
- 输出 LaTeX/PPT 可用代码?
告诉我你的需求!