Matplotlib pie() 函数
pie() 用于绘制饼图,展示各部分在整体中所占的比例关系。
饼图适用于展示少量分类(通常 5-8 个以内)的占比情况。
函数定义
pyplot 接口
matplotlib.pyplot.pie(x, explode=None, labels=None, colors=None,
autopct=None, pctdistance=0.6, shadow=False, labeldistance=1.1,
startangle=0, radius=1, counterclock=True, wedgeprops=None,
textprops=None, center=(0, 0), frame=False, rotatelabels=False, *,
normalize=True, hatch=None, **kwargs)
Axes 接口
Axes.pie(x, explode=None, labels=None, colors=None, autopct=None,
pctdistance=0.6, shadow=False, labeldistance=1.1, startangle=0,
radius=1, counterclock=True, wedgeprops=None, textprops=None,
center=(0, 0), frame=False, rotatelabels=False, *,
normalize=True, hatch=None, **kwargs)
参数说明
| 参数 | 类型 | 说明 |
|---|---|---|
| x | 1D array-like | 每个扇区的数值(必填),自动归一化 |
| explode | array-like | 每个扇区偏离中心的距离,0 表示不偏离 |
| labels | list | 每个扇区的标签文本 |
| colors | list | 每个扇区的颜色 |
| autopct | str 或 callable | 自动显示百分比,如 '%1.1f%%' 表示一位小数;None 不显示 |
| pctdistance | float | 百分比文本与圆心的距离比例,默认 0.6 |
| shadow | bool | 是否添加阴影效果 |
| labeldistance | float | 标签与圆心的距离比例,默认 1.1 |
| startangle | float | 第一个扇区的起始角度(逆时针方向),0 表示从 3 点钟方向开始 |
| radius | float | 饼图半径,默认 1 |
| counterclock | bool | 扇区方向:True 逆时针(默认),False 顺时针 |
| wedgeprops | dict | 传递给每个扇区 (Wedge) 的参数,如 {'edgecolor':'white', 'linewidth':1} |
| textprops | dict | 传递给文本的参数,如 {'fontsize':12, 'color':'gray'} |
| center | tuple | 饼图中心坐标,默认 (0, 0) |
| normalize | bool | 是否将 x 归一化使总和为 1,默认 True |
pie() 返回三个列表:
(patches, texts, autotexts)。patches 是扇区对象,texts 是标签文本,autotexts 是百分比文本。
使用示例
示例 1:基本饼图
实例
import matplotlib.pyplot as plt
# 数据
sizes = [30, 25, 20, 15, 10]
labels = ['Python', 'Java', 'JavaScript', 'C++', 'Go']
colors = ['#3498db', '#e74c3c', '#f39c12', '#2ecc71', '#9b59b6']
fig, ax = plt.subplots(layout='constrained')
# 绘制饼图
ax.pie(sizes, labels=labels, colors=colors,
autopct='%1.1f%%', # 显示百分比,保留一位小数
startangle=90, # 从 12 点钟方向开始
wedgeprops={'edgecolor': 'white', 'linewidth': 1})
ax.set_title('Programming Language Usage')
plt.show()
# 数据
sizes = [30, 25, 20, 15, 10]
labels = ['Python', 'Java', 'JavaScript', 'C++', 'Go']
colors = ['#3498db', '#e74c3c', '#f39c12', '#2ecc71', '#9b59b6']
fig, ax = plt.subplots(layout='constrained')
# 绘制饼图
ax.pie(sizes, labels=labels, colors=colors,
autopct='%1.1f%%', # 显示百分比,保留一位小数
startangle=90, # 从 12 点钟方向开始
wedgeprops={'edgecolor': 'white', 'linewidth': 1})
ax.set_title('Programming Language Usage')
plt.show()
示例 2:突出特定扇区 (explode)
实例
import matplotlib.pyplot as plt
sizes = [35, 25, 20, 12, 8]
labels = ['Search', 'Social', 'Direct', 'Email', 'Referral']
explode = (0.1, 0, 0, 0, 0) # 第一个扇区(Search)突出 0.1
fig, ax = plt.subplots(layout='constrained')
wedges, texts, autotexts = ax.pie(
sizes, labels=labels, explode=explode,
autopct='%1.1f%%', startangle=90,
colors=['#2ecc71', '#3498db', '#9b59b6', '#f39c12', '#e74c3c'],
wedgeprops={'edgecolor': 'white', 'linewidth': 1},
textprops={'fontsize': 11})
# 修改百分比文本的颜色
for autotext in autotexts:
autotext.set_color('white')
autotext.set_fontweight('bold')
ax.set_title('Website Traffic Sources', fontsize=14)
plt.show()
sizes = [35, 25, 20, 12, 8]
labels = ['Search', 'Social', 'Direct', 'Email', 'Referral']
explode = (0.1, 0, 0, 0, 0) # 第一个扇区(Search)突出 0.1
fig, ax = plt.subplots(layout='constrained')
wedges, texts, autotexts = ax.pie(
sizes, labels=labels, explode=explode,
autopct='%1.1f%%', startangle=90,
colors=['#2ecc71', '#3498db', '#9b59b6', '#f39c12', '#e74c3c'],
wedgeprops={'edgecolor': 'white', 'linewidth': 1},
textprops={'fontsize': 11})
# 修改百分比文本的颜色
for autotext in autotexts:
autotext.set_color('white')
autotext.set_fontweight('bold')
ax.set_title('Website Traffic Sources', fontsize=14)
plt.show()
示例 3:环形图(甜甜圈图)
实例
import matplotlib.pyplot as plt
sizes = [40, 30, 20, 10]
labels = ['Chrome (40%)', 'Safari (30%)', 'Firefox (20%)', 'Other (10%)']
fig, ax = plt.subplots(layout='constrained')
# 使用 wedgeprops 设置 width 创建环形图
wedges, texts = ax.pie(
sizes, labels=labels,
startangle=90,
colors=['#4285F4', '#34A853', '#FBBC05', '#EA4335'],
wedgeprops={'width': 0.4, # 扇区宽度(0~1),<1 则为环形
'edgecolor': 'white', 'linewidth': 2})
ax.set_title('Browser Market Share (Donut Chart)', fontsize=14)
plt.show()
sizes = [40, 30, 20, 10]
labels = ['Chrome (40%)', 'Safari (30%)', 'Firefox (20%)', 'Other (10%)']
fig, ax = plt.subplots(layout='constrained')
# 使用 wedgeprops 设置 width 创建环形图
wedges, texts = ax.pie(
sizes, labels=labels,
startangle=90,
colors=['#4285F4', '#34A853', '#FBBC05', '#EA4335'],
wedgeprops={'width': 0.4, # 扇区宽度(0~1),<1 则为环形
'edgecolor': 'white', 'linewidth': 2})
ax.set_title('Browser Market Share (Donut Chart)', fontsize=14)
plt.show()
示例 4:多级环形图
实例
import matplotlib.pyplot as plt
# 外层数据和内层数据
outer_sizes = [35, 30, 20, 15]
inner_sizes = [40, 30, 30]
outer_labels = ['Asia', 'Europe', 'America', 'Africa']
inner_labels = ['Mobile', 'Desktop', 'Tablet']
outer_colors = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4']
inner_colors = ['#FFE0B2', '#BBDEFB', '#C8E6C9']
fig, ax = plt.subplots(layout='constrained')
# 外圈
ax.pie(outer_sizes, radius=1.3,
labels=outer_labels,
labeldistance=1.1,
colors=outer_colors,
wedgeprops={'width': 0.3, 'edgecolor': 'white', 'linewidth': 2})
# 内圈
ax.pie(inner_sizes, radius=1.0,
labels=inner_labels,
labeldistance=0.75,
colors=inner_colors,
wedgeprops={'width': 0.3, 'edgecolor': 'white', 'linewidth': 2})
ax.set_title('Multi-level Donut Chart', fontsize=14)
plt.show()
# 外层数据和内层数据
outer_sizes = [35, 30, 20, 15]
inner_sizes = [40, 30, 30]
outer_labels = ['Asia', 'Europe', 'America', 'Africa']
inner_labels = ['Mobile', 'Desktop', 'Tablet']
outer_colors = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4']
inner_colors = ['#FFE0B2', '#BBDEFB', '#C8E6C9']
fig, ax = plt.subplots(layout='constrained')
# 外圈
ax.pie(outer_sizes, radius=1.3,
labels=outer_labels,
labeldistance=1.1,
colors=outer_colors,
wedgeprops={'width': 0.3, 'edgecolor': 'white', 'linewidth': 2})
# 内圈
ax.pie(inner_sizes, radius=1.0,
labels=inner_labels,
labeldistance=0.75,
colors=inner_colors,
wedgeprops={'width': 0.3, 'edgecolor': 'white', 'linewidth': 2})
ax.set_title('Multi-level Donut Chart', fontsize=14)
plt.show()
常见问题
饼图 vs 柱状图的适用场景?
饼图适合展示 5-8 个以内的分类占比,读者能直观感受整体中的份额。
分类过多(超过 8 个)或需要精确比较数值时,优先使用柱状图。
autopct 格式说明?
'%1.1f%%' 表示浮点数,总宽度至少 1 位,1 位小数,后面跟上 %%(百分号)。
也可传入函数,如 autopct=lambda pct: f'{pct:.1f}%'。

Matplotlib 参考文档