我如何使用 matplotlib autopct? [英] How do I use matplotlib autopct?

查看:29
本文介绍了我如何使用 matplotlib autopct?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'd like to create a matplotlib pie chart which has the value of each wedge written on top of the wedge.

文档建议我应该使用 autopct 来做这个.

The documentation suggests I should use autopct to do this.

autopct:[无|格式字符串 |格式功能]如果不是 None,则是用于标记楔形的字符串或函数他们的数值.标签将是放在楔子里面.如果是格式字符串,标签为fmt%pct.如果它是一个函数,它将被称为.

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.

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

Unfortunately, I'm unsure what this format string or format function is supposed to be.

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

Using this basic example below, how can I display each numerical value on top of its wedge?

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 enables you to display the percent value using Python string formatting. For example, if autopct='%.2f', then for each pie wedge, the format string is '%.2f' and the numerical percent value for that wedge is pct, so the wedge label is set to the string '%.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 提供可调用对象来做更有趣的事情.要同时显示百分比值和原始值,您可以执行以下操作:

You can do fancier things by supplying a callable to autopct. To display both the percent value and the original value, you could do this:

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

Again, for each pie wedge, matplotlib supplies the percent value pct as the argument, though this time it is sent as the argument to the function my_autopct. The wedge label is set to my_autopct(pct).

这篇关于我如何使用 matplotlib autopct?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆