How do I use matplotlib autopct?
我想创建一个matplotlib饼图,该饼图的每个楔形的值都写在楔形的顶部。
文档建议我应该使用
autopct: [ None | format string |
format function ]
If not None, is a string or function used to label the wedges with
their numeric value. The label will be
placed inside the wedge. If it is a
format string, the label will be
fmt%pct. If it is a function, it will
be called.
不幸的是,我不确定此格式字符串或格式函数应该是什么。
使用下面的基本示例,如何在楔形顶部显示每个数值?
1 2 3 4 5 | plt.figure() values = [3, 12, 5, 8] labels = ['a', 'b', 'c', 'd'] plt.pie(values, labels=labels) #autopct?? plt.show() |
1 2 3 4 5 6 | 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() |
产量
您可以通过向
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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将百分比值
您可以执行以下操作:
1 | plt.pie(values, labels=labels, autopct=lambda p : '{:.2f}% ({:,.0f})'.format(p,p * sum(values)/100)) |
使用lambda和格式可能更好
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | import pandas as pd import matplotlib.pyplot as plt import seaborn as sns path = r"C:\\Users\\byqpz\\Desktop\\DATA\ aw\\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() |
1 | val=int(pct*total/100.0) |
应为
1 | val=int((pct*total/100.0)+0.5) |
防止舍入错误。
借助matplotlib画廊和StackOverflow用户的提示,我想到了以下饼图。
autopct显示成分的数量和种类。
1 2 3 4 5 6 7 8 9 10 11 12 | import matplotlib.pyplot as plt %matplotlib inline reciepe= ["480g Flour","50g Eggs","90g Sugar"] amt=[int(x.split('g ')[0]) for x in reciepe] ing=[x.split()[-1] for x in reciepe] fig, ax=plt.subplots(figsize=(5,5), subplot_kw=dict(aspect='equal')) wadges, text, autotext=ax.pie(amt, labels=ing, startangle=90, autopct=lambda p:"{:.0f}g\ ({:.1f})%".format(p*sum(amt)/100, p), textprops=dict(color='k', weight='bold', fontsize=8)) ax.legend(wadges, ing,title='Ingredents', loc='best', bbox_to_anchor=(0.35,0.85,0,0)) |
Piechart显示样本配方成分的数量和百分比
饼图显示编程语言用户的薪水和百分比
例如,
1 2 | autopct = '%.1f' # display the percentage value to 1 decimal place autopct = '%.2f' # display the percentage value to 2 decimal places |
如果要在饼图中显示%符号,则必须编写/添加:
1 2 | autopct = '%.1f%%' autopct = '%.2f%%' |
由于
1 | autopct = lambda p:f'{p:.2f}%' |
,或者在某些情况下,您可以将数据标记为
1 | autopct = lambda p:'any text you want' |
,并为您的代码显示百分比,您可以使用:
1 2 3 4 5 | plt.figure() values = [3, 12, 5, 8] labels = ['a', 'b', 'c', 'd'] plt.pie(values, labels=labels, autopct=lambda p:f'{p:.2f}%, {p*sum(values)/100 :.0f} items') plt.show() |
,结果将类似于: