我想创建一个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()
你可以:
应该是
以防止舍入误差。
autopct
允许您使用Python字符串格式显示百分比值。例如,如果autopct='%.2f'
,则对于每个饼图楔块,格式字符串为'%.2f'
,并且该楔块的数值百分比为pct
,因此楔块标签设置为字符串'%.2f'%pct
。收益率
您可以通过为
autopct
提供一个可调用的来做一些更奇特的事情。要同时显示百分比值和原始值,可以执行以下操作:同样,对于每个饼图楔块,matplotlib提供百分比值
pct
作为参数,尽管这次它作为参数发送到函数my_autopct
。楔形标签设置为my_autopct(pct)
。相关问题 更多 >
编程相关推荐