本文目录导读:

我来为你展示几个Python绘制饼图的实用案例,从基础到进阶。
基础饼图
import matplotlib.pyplot as plt
import numpy as np
# 准备数据
labels = ['苹果', '香蕉', '橙子', '葡萄', '其他']
sizes = [30, 25, 20, 15, 10] # 占比数据
colors = ['#ff9999', '#66b3ff', '#99ff99', '#ffcc99', '#c2c2f0']
# 创建图形
plt.figure(figsize=(8, 6))
plt.pie(sizes, labels=labels, colors=colors, autopct='%1.1f%%',
startangle=90)
'水果销售占比', fontsize=14)
plt.axis('equal') # 确保饼图是圆的
plt.show()
带突出显示的饼图
# 突出显示某个扇区
explode = (0.1, 0, 0, 0, 0) # 只突出第一个扇区
plt.figure(figsize=(10, 8))
plt.pie(sizes, explode=explode, labels=labels, colors=colors,
autopct='%1.1f%%', shadow=True, startangle=90,
textprops={'fontsize': 12})
'水果销售占比(突出显示苹果)', fontsize=14)
plt.show()
环形图(甜甜圈图)
# 创建环形图
plt.figure(figsize=(10, 8))
wedges, texts, autotexts = plt.pie(sizes, labels=labels, colors=colors,
autopct='%1.1f%%', startangle=90,
pctdistance=0.85)
# 在中心添加白色圆创建环形效果
centre_circle = plt.Circle((0, 0), 0.70, fc='white')
fig = plt.gcf()
fig.gca().add_artist(centre_circle)
'水果销售环形图', fontsize=14)
plt.axis('equal')
plt.show()
带图例的饼图
plt.figure(figsize=(12, 8))
patches, texts, autotexts = plt.pie(sizes, colors=colors,
autopct='%1.1f%%', startangle=90,
pctdistance=0.7)
# 设置文本样式
for text in texts:
text.set_fontsize(12)
for autotext in autotexts:
autotext.set_fontsize(10)
autotext.set_color('white')
# 添加图例
plt.legend(patches, labels, title="水果种类", loc="center left",
bbox_to_anchor=(1, 0, 0.5, 1))
'水果销售占比(带图例)', fontsize=14)
plt.tight_layout()
plt.show()
多子图饼图
# 创建多个子图
fig, axes = plt.subplots(1, 3, figsize=(15, 5))
# 不同数据集
data1 = [30, 25, 20, 15, 10]
data2 = [40, 20, 20, 10, 10]
data3 = [25, 25, 25, 15, 10]
s = ['第一季度', '第二季度', '第三季度']
datasets = [data1, data2, data3]
for ax, data, title in zip(axes, datasets, titles):
ax.pie(data, labels=labels, colors=colors, autopct='%1.1f%%',
startangle=90)
ax.set_title(title, fontsize=12)
ax.axis('equal')
plt.suptitle('各季度水果销售占比对比', fontsize=14)
plt.tight_layout()
plt.show()
自定义颜色和样式
import matplotlib.pyplot as plt
# 自定义颜色方案
custom_colors = ['#e74c3c', '#3498db', '#2ecc71', '#f39c12', '#9b59b6']
explode = (0.05, 0.05, 0.05, 0.05, 0.05) # 所有扇区轻微突出
plt.figure(figsize=(10, 8))
plt.pie(sizes, explode=explode, labels=labels, colors=custom_colors,
autopct='%1.1f%%', shadow=True, startangle=90,
textprops={'fontsize': 12, 'fontweight': 'bold'})
plt.title('水果销售占比分析\n(2024年第一季度)', fontsize=14,
fontweight='bold', pad=20)
plt.axis('equal')
plt.show()
实用函数封装
def create_pie_chart(data, labels, title='占比图', colors=None,
explode=None, shadow=True, startangle=90):
"""
创建饼图的通用函数
参数:
data: 数据列表
labels: 标签列表 图表标题
colors: 颜色列表
explode: 突出显示设置
shadow: 是否显示阴影
startangle: 起始角度
"""
plt.figure(figsize=(10, 8))
if explode is None:
explode = [0] * len(data) # 默认不突出
if colors is None:
colors = plt.cm.Set3(np.linspace(0, 1, len(data)))
wedges, texts, autotexts = plt.pie(data, explode=explode,
labels=labels, colors=colors,
autopct='%1.1f%%',
shadow=shadow,
startangle=startangle)
# 美化文本
for text in texts:
text.set_fontsize(11)
for autotext in autotexts:
autotext.set_fontsize(10)
autotext.set_color('white')
plt.title(title, fontsize=14, fontweight='bold')
plt.axis('equal')
plt.tight_layout()
plt.show()
return wedges, texts, autotexts
# 使用函数
data = [35, 25, 20, 12, 8]
labels = ['产品A', '产品B', '产品C', '产品D', '产品E']
create_pie_chart(data, labels, title='产品销售占比')
保存图表
# 创建并保存高质量的饼图
plt.figure(figsize=(10, 8), dpi=100)
plt.pie(sizes, labels=labels, colors=colors, autopct='%1.1f%%',
shadow=True, startangle=90)'水果销售占比', fontsize=14)
plt.axis('equal')
# 保存为不同格式
plt.savefig('pie_chart.png', dpi=300, bbox_inches='tight') # PNG格式
plt.savefig('pie_chart.pdf', bbox_inches='tight') # PDF格式
plt.savefig('pie_chart.svg', bbox_inches='tight') # SVG格式
plt.show()
关键参数说明
| 参数 | 说明 | 示例值 |
|---|---|---|
x |
数据值 | [30, 25, 20, 15, 10] |
labels |
各扇区标签 | ['A', 'B', 'C'] |
colors |
自定义颜色 | ['red', 'blue', 'green'] |
autopct |
显示百分比格式 | '%1.1f%%' |
explode |
突出显示扇区 | (0.1, 0, 0) |
shadow |
是否显示阴影 | True/False |
startangle |
起始角度 | 90 |
pctdistance |
百分比文本距离 | 85 |
这些代码示例覆盖了饼图绘制的常用场景,你可以根据实际需求进行修改和组合。