如何使用matplotlib autoct?

2024-04-26 20:19:10 发布

您现在位置:Python中文网/ 问答频道 /正文

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

documentation建议我使用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.

不幸的是,我不确定这个格式字符串或格式函数应该是什么。

使用下面的基本示例,如何在其楔形顶部显示每个数值?

plt.figure()
values = [3, 12, 5, 8] 
labels = ['a', 'b', 'c', 'd'] 
plt.pie(values, labels=labels) #autopct??
plt.show()

Tags: thenoneformatstringlabelsifisit
3条回答

你可以:

plt.pie(values, labels=labels, autopct=lambda p : '{:.2f}%  ({:,.0f})'.format(p,p * sum(values)/100))
val=int(pct*total/100.0)

应该是

val=int((pct*total/100.0)+0.5)

以防止舍入误差。

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

收益率 Simple pie chart with percentages

您可以通过为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()

Pie chart with both percentages and absolute numbers.

同样,对于每个饼图楔块,matplotlib提供百分比值pct作为参数,尽管这次它作为参数发送到函数my_autopct。楔形标签设置为my_autopct(pct)

相关问题 更多 >