本文目录导读:

在Python中绘制饼状统计图,最常用的库是 Matplotlib,下面我会先给出一个基础案例,然后展示如何自定义样式,最后介绍一些高级技巧。
基础饼状图
import matplotlib.pyplot as plt
# 准备数据
labels = ['苹果', '香蕉', '橙子', '葡萄', '西瓜']
sizes = [30, 25, 20, 15, 10] # 百分比数值
colors = ['#ff9999', '#66b3ff', '#99ff99', '#ffcc99', '#c2c2f0'] # 可选颜色
# 创建饼状图
plt.pie(sizes, labels=labels, colors=colors, autopct='%1.1f%%')
plt.title('水果销售占比')
# 显示图形
plt.show()
输出效果:
- 一个标准的饼状图,每块显示标签和百分比
带分离效果的饼状图(突出某一块)
import matplotlib.pyplot as plt
labels = ['苹果', '香蕉', '橙子', '葡萄', '西瓜']
sizes = [30, 25, 20, 15, 10]
colors = ['#ff9999', '#66b3ff', '#99ff99', '#ffcc99', '#c2c2f0']
# explode参数用于将某块分离出来(0表示不分离,数值越大分离越远)
explode = (0.1, 0, 0, 0, 0) # 苹果突出10%
plt.pie(sizes,
labels=labels,
colors=colors,
explode=explode,
autopct='%1.1f%%',
shadow=True, # 添加阴影效果
startangle=90) # 从90度开始绘制(顶部)
'水果销售占比(苹果突出显示)')
plt.axis('equal') # 确保饼状图是正圆
plt.show()
带图例和自定义样式的饼状图
import matplotlib.pyplot as plt
labels = ['苹果', '香蕉', '橙子', '葡萄', '西瓜']
sizes = [30, 25, 20, 15, 10]
colors = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', '#FFEAA7']
# 自定义饼状图
plt.figure(figsize=(8, 6))
wedges, texts, autotexts = plt.pie(sizes,
labels=labels,
colors=colors,
autopct='%1.1f%%',
pctdistance=0.8, # 百分比文字距离圆心的距离
labeldistance=1.1, # 标签距离圆心的距离
startangle=90,
wedgeprops={'linewidth': 2, 'edgecolor': 'white'}) # 添加白色边框
# 自定义文字样式
for text in texts:
text.set_fontsize(12)
text.set_fontweight('bold')
for autotext in autotexts:
autotext.set_fontsize(10)
autotext.set_color('white')
autotext.set_fontweight('bold')
'水果销售占比分析', fontsize=16, fontweight='bold', pad=20)
plt.legend(labels, loc='lower right', bbox_to_anchor=(1.3, 0.5)) # 添加图例
plt.tight_layout()
plt.show()
环形饼状图(甜甜圈图)
import matplotlib.pyplot as plt
labels = ['苹果', '香蕉', '橙子', '葡萄', '西瓜']
sizes = [30, 25, 20, 15, 10]
colors = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', '#FFEAA7']
# 创建环形图(在中间添加一个白色圆)
plt.figure(figsize=(8, 6))
plt.pie(sizes,
labels=labels,
colors=colors,
autopct='%1.1f%%',
startangle=90,
pctdistance=0.75,
wedgeprops={'width': 0.4}) # width控制环的宽度
# 或者在中间画一个白圆
# centre_circle = plt.Circle((0, 0), 0.6, fc='white')
# fig = plt.gcf()
# fig.gca().add_artist(centre_circle)
'水果销售占比(环形图)', fontsize=14, fontweight='bold')
plt.axis('equal')
plt.tight_layout()
plt.show()
从CSV文件读取数据绘制饼状图
import matplotlib.pyplot as plt
import pandas as pd
# 读取数据(假设有 sales.csv 文件)
# sales.csv 内容示例:
# product,quantity
# 苹果,150
# 香蕉,125
# 橙子,100
# 葡萄,75
# 西瓜,50
df = pd.read_csv('sales.csv')
# 提取数据和标签
labels = df['product'].tolist()
sizes = df['quantity'].tolist()
# 计算百分比
sizes_pct = [x / sum(sizes) * 100 for x in sizes]
# 绘制饼状图
plt.figure(figsize=(8, 6))
plt.pie(sizes_pct,
labels=labels,
autopct='%1.1f%%',
startangle=90,
shadow=True)
'产品销售占比')
plt.axis('equal')
plt.show()
实用技巧总结
常用参数说明:
| 参数 | 说明 | 示例值 |
|---|---|---|
x |
数据值(会自动计算百分比) | [30, 25, 20, 15, 10] |
labels |
每个扇区的标签 | ['A', 'B', 'C'] |
colors |
自定义颜色 | ['red', 'blue'] |
autopct |
显示百分比格式 | '%1.1f%%' |
explode |
扇区分离距离 | (0.1, 0, 0) |
shadow |
是否显示阴影 | True/False |
startangle |
起始角度 | 90(从顶部开始) |
pctdistance |
百分比文字距圆心距离 | 8 |
labeldistance |
标签距圆心距离 | 1 |
wedgeprops |
扇区属性 | {'edgecolor': 'white'} |
注意事项:
- 数据总和:数据会自动计算百分比,不需要手动计算
- 正圆显示:使用
plt.axis('equal')确保饼状图为正圆 - 颜色选择:使用调色板或十六进制颜色代码让图表更美观
- 中文字体:如果显示中文乱码,需要设置中文字体:
plt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文 plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号
安装所需的库
pip install matplotlib pandas
这些案例覆盖了 Python 绘制饼状统计图的常见场景,你可以根据实际需求进行调整。