Matplotlib学习---用matplotlib画饼图/面包圈图(pie chart, donut chart)

时间:2023-03-08 16:21:23

我在网上随便找了一组数据,用它来学习画图。大家可以直接把下面的数据复制到excel里,然后用pandas的read_excel命令读取。或者直接在脚本里创建该数据。

Matplotlib学习---用matplotlib画饼图/面包圈图(pie chart, donut chart)

饼图: ax.pie(x,labels=...,explode=...)

代码如下:

import numpy as np
import matplotlib
from matplotlib import pyplot as plt
matplotlib.rcParams['font.sans-serif']='Microsoft Yahei' #改字体为微软雅黑,以便显示中文
fig,ax=plt.subplots() animal={"锯齿动物":38,"蝙蝠类":21.8,"食虫类":8.2,"灵长类":8,"其他":6.9,"有袋类":6.5,"食肉类":5.6,"偶蹄类":5} #创建数据
data=np.array([i for i in animal.values()]).astype(float) #饼图显示数据,将其转换成float格式
explode=[0.1,0,0,0,0,0,0,0] #设置突出显示的内容,这里为突出显示第一项
label=np.array([j for j in animal.keys()]) #设置标签
ax.pie(data,labels=label,autopct='%.1f%%',explode=explode,startangle=90,counterclock=False) #autopct为显示百分比,startangle为起始角度,counterclock逆时针选否
ax.set_title("哺乳动物类群") #设置标题
ax.axis("equal") #设置x轴和y轴等长,否则饼图将不是一个正圆 plt.show()

图像如下:

Matplotlib学习---用matplotlib画饼图/面包圈图(pie chart, donut chart)

需要注意的是:所有类别的百分比相加应为100%,千万不要出现少于或大于100%的情况。

还有一种图是面包圈图,就是饼中心是空的。可以通过设置ax.pie命令里的wedgeprops参数来达到此效果。

还是以上面的数据为例,来画面包圈图:

import numpy as np
import matplotlib
from matplotlib import pyplot as plt
matplotlib.rcParams['font.sans-serif']='Microsoft Yahei' #改字体为微软雅黑,以便显示中文
fig,ax=plt.subplots() animal={"锯齿动物":38,"蝙蝠类":21.8,"食虫类":8.2,"灵长类":8,"其他":6.9,"有袋类":6.5,"食肉类":5.6,"偶蹄类":5} #创建数据
data=np.array([i for i in animal.values()]).astype(float) #饼图显示数据,将其转换成float格式
label=np.array([j for j in animal.keys()]) #设置标签
ax.pie(data,labels=label,autopct='%.1f%%',startangle=90,counterclock=False,wedgeprops=dict(width=0.6,edgecolor='w')) #autopct为显示百分比,startangle为起始角度,counterclock逆时针选否
ax.set_title("哺乳动物类群") #设置标题
ax.axis("equal") #设置x轴和y轴等长,否则饼图将不是一个正圆 plt.show()

图像如下:

Matplotlib学习---用matplotlib画饼图/面包圈图(pie chart, donut chart)