如何使用matplotlib的autopct?
我想用matplotlib画一个饼图,并在每个扇形的上面写上它的数值。
文档建议我使用 autopct
来实现这个功能。
autopct: [ None | 格式字符串 | 格式函数 ] 如果不是None,它可以是一个字符串或函数,用来给扇形标记上它们的数值。这个标记会放在扇形内部。如果是格式字符串,标记的格式是 fmt%pct。如果是一个函数,它会被调用。
可惜的是,我不太明白这个格式字符串或格式函数应该是什么样的。
在下面这个简单的例子中,我该如何在每个扇形的上面显示它的数值呢?
plt.figure()
values = [3, 12, 5, 8]
labels = ['a', 'b', 'c', 'd']
plt.pie(values, labels=labels) #autopct??
plt.show()
7 个回答
14
使用lambda和format可能会更好
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
path = r"C:\Users\byqpz\Desktop\DATA\raw\tips.csv"
df = pd.read_csv(path, engine='python', encoding='utf_8_sig')
days = df.groupby('day').size()
sns.set()
days.plot(kind='pie', title='Number of parties on different days', figsize=[8,8],
autopct=lambda p: '{:.2f}%({:.0f})'.format(p,(p/100)*days.sum()))
plt.show()
17
你可以这样做:
plt.pie(values, labels=labels, autopct=lambda p : '{:.2f}% ({:,.0f})'.format(p,p * sum(values)/100))
167
autopct
这个功能可以让你用Python的字符串格式化来显示百分比的数值。比如说,如果你设置 autopct='%.2f'
,那么每个饼图的部分(也就是“饼块”)就会用 '%.2f'
这个格式来显示,而这个饼块的百分比数值用 pct
表示,所以饼块的标签就会变成 '%.2f'%pct
这样的字符串。
import matplotlib.pyplot as plt
plt.figure()
values = [3, 12, 5, 8]
labels = ['a', 'b', 'c', 'd']
plt.pie(values, labels=labels, autopct='%.2f')
plt.show()
这样就会得到
如果你想做得更花哨一点,可以给 autopct
提供一个可调用的函数。比如说,如果你想同时显示百分比和原始数值,可以这样做:
import matplotlib.pyplot as plt
# make the pie circular by setting the aspect ratio to 1
plt.figure(figsize=plt.figaspect(1))
values = [3, 12, 5, 8]
labels = ['a', 'b', 'c', 'd']
def make_autopct(values):
def my_autopct(pct):
total = sum(values)
val = int(round(pct*total/100.0))
return '{p:.2f}% ({v:d})'.format(p=pct,v=val)
return my_autopct
plt.pie(values, labels=labels, autopct=make_autopct(values))
plt.show()
同样地,对于每个饼块,matplotlib 会把百分比数值 pct
作为参数传给你定义的函数 my_autopct
。然后饼块的标签就会设置为 my_autopct(pct)
的结果。