关于python:如何使用matplotlib autopct?

How do I use matplotlib autopct?

我想创建一个matplotlib饼图,该饼图的每个楔形的值都写在楔形的顶部。

文档建议我应该使用autopct来执行此操作。

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()

autopct使您可以使用Python字符串格式显示百分比值。例如,如果autopct='%.2f',则对于每个饼图楔,格式字符串为'%.2f',并且该楔形的数值百分比值为pct,因此,楔形标签设置为字符串'%.2f'%pct

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()

产量
Simple

您可以通过向autopct提供可调用对象来做更奇特的事情。要显示百分比值和原始值,可以执行以下操作:

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()

Pie


您可以执行以下操作:

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()

enter


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显示样本配方成分的数量和百分比

饼图显示编程语言用户的薪水和百分比


autopct使您可以使用Python字符串格式显示每个切片的百分比值。

例如,

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%%'

由于autopct是用于用楔形数值标记楔形的功能,因此您可以根据需要在其中写入任何标签或格式化项目数量。对我而言,显示百分比标签的最简单方法是使用lambda:

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()

,结果将类似于:

result