14.Matplotlib-绘制饼图
image
扫码关注【牵引小哥讲Python】,关注回复【资源】领取学习资源!
原创作者:牵引小哥
微信公众号:牵引小哥讲Python
注:转载或复制请注明出处——牵引小哥
本期小哥主要讲解饼图的绘制方法。在Matplotlib中使用ax.pie()
函数绘制饼图。官方参考链接:
https://matplotlib.org/api/_as_gen/matplotlib.pyplot.pie.html#matplotlib.pyplot.pie
1. ax.pie()
的基础用法
ax.pie(x, explode=None, labels=None, colors=None, autopct=None, shadow=False, startangle=None, radius=None, textprops=None, ...)
关键参数说明:
- x:数据序列
- explode:扇形块远离圆心的举例
- labels:数据对应标签
- colors:颜色
- autopct:用于指定每个扇形块标注文本的样式,比如:定义百分数精度
- shadow:阴影
- startangle:起始角度(逆时针顺序绘图)
- radius:饼图半径
- textprops:图中文本属性
应用举例:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
mpl.rcParams['font.size'] = 16
mpl.rcParams['figure.figsize'] = (7,5)
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
plt.style.use('ggplot')
#%% 基础用法
labels = ['折线图', '条形图', '直方图', '散点图', '饼图']
ratio = [40, 25, 15, 12, 8]
explode = (0.1, 0.1, 0, 0, 0) #设置“爆炸”距离
# labels、ratio、explode各变量值存在对应关系
fig, ax = plt.subplots()
ax.pie(ratio, labels=labels, autopct='%1.1f%%', explode=explode,
shadow=True, startangle=90, textprops={'color':'b', 'size':14},
labeldistance=None)
ax.axis('equal') # 等宽高比确保饼图被画成圆形
plt.show()
plt.tight_layout()
对于labels
也可通过legend
显示。
#labeldistance=None,取消标签在周围显示
ax.pie(ratio, labels=labels, autopct='%1.1f%%', explode=explode,
shadow=True, startangle=90, textprops={'color':'w', 'size':14},
labeldistance=None)
ax.legend(loc='upper right')
2. 进阶用法
ax.pie()
函数的返回值有三个:
- patches:每个扇形对应的颜色,list类型
- texts:每个扇形对应的label,list类型
- autotexts:每个扇形对应的数值标注,list类型
在进阶用法中,小哥结合Python的格式化输出和 ax.pie()
返回值,示范如何将每个扇区对应的数量标注到图中。
data = ['40 个 折线图 ', '25 个 条形图',
'15 个 直方图', '12 个 散点图',
'8 个 饼图']
## 拆分原始数据得到数字,图层标签
num = [float(x.split()[0]) for x in data]
labels = [x.split()[-1] for x in data]
## 定义函数,格式化输出标记内容,包含百分比和个数
def MarkText(pct, text):
absolute = int(pct/100.*np.sum(text))
return "{:.1f}%\n({:d} 个)".format(pct, absolute)
fig, ax = plt.subplots()
#使用lambda函数调用MarkText函数
patches, texts, autotexts = ax.pie(num, autopct=lambda pct: MarkText(pct, num),
startangle=90, radius=0.6,
textprops=dict(color="w"))
ax.legend(patches, labels, loc="center right")
ax.axis('equal') # 等宽高比确保饼图被画成圆形