使用 matplotlib 创建一个饼图

Create a pie with matplotlib

你好,我有这个代码 Python :

import matplotlib.pyplot as plt

total_a = 0.004095232
total_b = 0.05075945
total_c = 0.005425
total_d = 0.022948572
total_e = 0.015012

slices = [total_a,total_b,total_c,total_d,total_e]
activities = ['a', 'b', 'c', 'd','e']
cols = ['gold', 'yellowgreen', 'lightcoral', 'lightskyblue', 'orangered']
plt.pie(slices,labels=activities,autopct='%1.1f%%',colors=cols,startangle=140,shadow=True)
plt.show()

但是当我执行这段代码时我得到了这个:

我不明白为什么我没有得到一个完整的馅饼? 感谢您的帮助!

根据下面 ImportanceOfBeingErnest 的回答以及对 documentation 的解释,plt.py 采用数组输入,只要元素之和大于 1,就会为您规范化值。

由于您的值总和小于 1,因此数组未标准化。为了使自己正常化,您应该使用以下行将每个元素除以列表的最大值:

slices = [aSlice/max(slices) for aSlice in slices]

我会把它放在你的程序中:

import matplotlib.pyplot as plt

total_a = 0.004095232
total_b = 0.05075945
total_c = 0.005425
total_d = 0.022948572
total_e = 0.015012


slices = [total_a,total_b,total_c,total_d,total_e]
slices = [aSlice/max(slices) for aSlice in slices]

activities = ['a', 'b', 'c', 'd','e']
cols = ['gold', 'yellowgreen', 'lightcoral', 'lightskyblue', 'orangered']
plt.pie(slices,labels=activities,autopct='%1.1f%%',colors=cols,startangle=140,shadow=True)
plt.show()

对我来说,这会生成如下图表:

xpie(x, ...) 的参数区分了两种情况。作为 the documentation states:

Make a pie chart of array x. The fractional area of each wedge is given by x/sum(x). If sum(x) < 1, then the values of x give the fractional area directly and the array will not be normalized. The resulting pie will have an empty wedge of size 1 - sum(x).

从问题的情况来看,总和确实小了sum(x) < 1。一个简单的解决方法可能是将输入数组乘以某个大数或除以它的总和。

slices = np.array([total_a,total_b,total_c,total_d,total_e])*100

slices = np.array([total_a,total_b,total_c,total_d,total_e])
slices /= slices.sum()