1.饼形图简介
饼形图常用于统计模型,它可以清晰明了地显示各项之间的相对大小或者占总体的比例大小,应用范围很广。
2.核心函数及核心参数介绍
pie(x,explode,labels,colors,autopct,shadow,radius)
常用参数介绍
x--要绘制的数据;
explode--指定各部分的偏移量,序列长度必须与x长度相同;
labels--指定各部分的标签,序列长度必须与x长度相同;
colors--指定各部分的颜色,序列长度必须与x长度相同;
autopct--饼图上数据标签的显示方式,可以显示为百分比或者通过自定义函数显示具体数据大小;
shadow--是否显示阴影,默认为False,设置为True,则显示阴影效果。
radius--饼形图的半径;
备注:上述参数中可仅给出x取值,其余参数均可缺省。
3.简单饼形图实例展示
import matplotlib.pyplot as plt# 数据labels = ['A', 'B', 'C', 'D']x = [10, 25, 30, 40]# 设置2行2列的子图plt.rc('font', family='STSong')fig, ax = plt.subplots(nrows=2, ncols=2)# 子图1ax[0,0].pie(x, labels=labels, autopct='%.2f%%')ax[0,0].set_title('子图1')# 子图2ax[0,1].pie(x, explode=[0.2, 0, 0.3, 0], labels=labels, autopct='%.2f%%')ax[0,1].set_title('子图2')# 子图3ax[1,0].pie(x, labels=labels, autopct='%.2f%%', shadow=True, radius=1.2)ax[1,0].set_title('子图3')# 子图4ax[1,1].pie(x, explode=[0.2, 0, 0.3, 0], labels=labels, autopct='%.2f%%', shadow=True)ax[1,1].set_title('子图4')plt.tight_layout()plt.show()
![845999a51ff72220591c4dc4a36bd503.png](https://i-blog.csdnimg.cn/blog_migrate/5fb5dadf400138f014de94afcf6b66c0.jpeg)
上述代码结果图
注意:饼形图上标记数据为百分比例,而非原绝对数据大小。
4.附带独立标签的饼形图展示
import matplotlib.pyplot as plt# 数据labels = ['A', 'B', 'C', 'D']x = [10, 25, 30, 40]plt.rc('font', family='STSong')fig, (ax1,ax2) = plt.subplots(nrows=2, ncols=1)plt.rc('font', family='STSong')# 子图1wedges, _, _ = ax1.pie(x, autopct=lambda pct:int(pct*sum(x)/100), shadow=True, radius=1.2)ax1.set_title('子图1')ax1.legend(wedges, labels, loc='center right', bbox_to_anchor=(0.80, 0.25, 0.6, 0.6), , fontsize=10)# 子图2wedges, _, _ = ax2.pie(x, autopct='%.2f%%', shadow=True, radius=1.2)ax2.set_title('子图2')ax2.legend(wedges, labels, loc='center right', bbox_to_anchor=(0.80, 0.25, 0.6, 0.6), , fontsize=10)plt.tight_layout()plt.show()
![e7825b5f120c44962b473c36009557f2.png](https://i-blog.csdnimg.cn/blog_migrate/01428464a98e38456167bf4c265f840b.jpeg)
上述代码结果图
注意:上述通过设置autopct参数来控制图中显示数据为实际数据大小或百分比大小。
参考资料
https://matplotlib.org/api/_as_gen/matplotlib.pyplot.pie.html#matplotlib.pyplot.pie
https://matplotlib.org/gallery/pie_and_polar_charts/pie_and_donut_labels.html#sphx-glr-gallery-pie-and-polar-charts-pie-and-donut-labels-py
https://matplotlib.org/gallery/pie_and_polar_charts/pie_demo2.html#sphx-glr-gallery-pie-and-polar-charts-pie-demo2-py