如何在matplotlib饼图中显示实际值(Python)?(How to have actual values in matplotlib Pie Chart displayed (Python)?

编程入门 行业动态 更新时间:2024-10-20 16:44:04
如何在matplotlib饼图中显示实际值(Python)?(How to have actual values in matplotlib Pie Chart displayed (Python)?)

我有一个饼图,绘制从CSV文件中提取的值。 当前显示的值的比例显示百分比“autopct ='%1.1f %%'”。 有没有办法显示每个切片的数据集中表示的实际值。

#Pie for Life Expectancy in Boroughs import pandas as pd import matplotlib import matplotlib.pyplot as plt # show plots inline %matplotlib inline # use ggplot style matplotlib.style.use('ggplot') #read data lifeEx = pd.read_csv('LEpie.csv') #Select columns df = pd.DataFrame() df['LB'] = lifeEx[['Regions']] df['LifeEx'] = lifeEx[['MinLF']] colorz = ['#B5DF00','#AD1FFF', '#BF1B00','#5FB1FF','#FFC93F'] exploda = (0, 0, 0, 0.1, 0) #plotting plt.pie(df['LifeEx'], labels=df['LB'], colors=colorz, autopct='%1.1f%%', explode = exploda, shadow = True,startangle=90) #labeling plt.title('Min Life expectancy across London Regions', fontsize=12)

I have a pie chart drawing the values extracted from a CSV file. The proportion of the values are currently displayed with the percentage displayed "autopct='%1.1f%%'". Is there a way to display the actual values which are represented in the dataset for each slice.

#Pie for Life Expectancy in Boroughs import pandas as pd import matplotlib import matplotlib.pyplot as plt # show plots inline %matplotlib inline # use ggplot style matplotlib.style.use('ggplot') #read data lifeEx = pd.read_csv('LEpie.csv') #Select columns df = pd.DataFrame() df['LB'] = lifeEx[['Regions']] df['LifeEx'] = lifeEx[['MinLF']] colorz = ['#B5DF00','#AD1FFF', '#BF1B00','#5FB1FF','#FFC93F'] exploda = (0, 0, 0, 0.1, 0) #plotting plt.pie(df['LifeEx'], labels=df['LB'], colors=colorz, autopct='%1.1f%%', explode = exploda, shadow = True,startangle=90) #labeling plt.title('Min Life expectancy across London Regions', fontsize=12)

最满意答案

使用autopct关键字

我们知道显示的百分比乘以所有实际值的总和必须是实际值,我们可以将其定义为函数,并使用autopct关键字将此函数提供给plt.pie 。

import matplotlib.pyplot as plt import numpy labels = 'Frogs', 'Hogs', 'Dogs' sizes = numpy.array([5860, 677, 3200]) colors = ['yellowgreen', 'gold', 'lightskyblue'] def absolute_value(val): a = numpy.round(val/100.*sizes.sum(), 0) return a plt.pie(sizes, labels=labels, colors=colors, autopct=absolute_value, shadow=True) plt.axis('equal') plt.show()

必须小心,因为计算涉及一些错误,因此提供的值仅精确到一些小数位。

稍微更高级的可能是以下函数,它试图通过比较计算值和输入数组之间的差异来从输入数组中获取原始值。 该方法不存在不准确的问题,但依赖于彼此充分不同的输入值。

def absolute_value2(val): a = sizes[ numpy.abs(sizes - val/100.*sizes.sum()).argmin() ] return a

饼图创建后更改文本

另一个选择是首先让饼图用百分比值绘制,然后替换它们。 为此,可以存储plt.pie()返回的autopct标签,并在其上循环以使用原始数组中的值替换文本。 注意, plt.pie()只返回三个参数,最后一个是感兴趣的标签,当提供autopct关键字时,我们在这里将它设置为空字符串。

labels = 'Frogs', 'Hogs', 'Dogs' sizes = numpy.array([5860, 677, 3200]) colors = ['yellowgreen', 'gold', 'lightskyblue'] p, tx, autotexts = plt.pie(sizes, labels=labels, colors=colors, autopct="", shadow=True) for i, a in enumerate(autotexts): a.set_text("{}".format(sizes[i])) plt.axis('equal') plt.show()

Using the autopct keyword

As we know that the percentage shown times the sum of all actual values must be the actual value, we can define this as a function and supply this function to plt.pie using the autopct keyword.

import matplotlib.pyplot as plt import numpy labels = 'Frogs', 'Hogs', 'Dogs' sizes = numpy.array([5860, 677, 3200]) colors = ['yellowgreen', 'gold', 'lightskyblue'] def absolute_value(val): a = numpy.round(val/100.*sizes.sum(), 0) return a plt.pie(sizes, labels=labels, colors=colors, autopct=absolute_value, shadow=True) plt.axis('equal') plt.show()

Care must be taken since the calculation involves some error, so the supplied value is only accurate to some decimal places.

A little bit more advanced may be the following function, that tries to get the original value from the input array back by comparing the difference between the calculated value and the input array. This method does not have the problem of inaccuracy but relies on input values which are sufficiently distinct from one another.

def absolute_value2(val): a = sizes[ numpy.abs(sizes - val/100.*sizes.sum()).argmin() ] return a

Changing text after pie creation

The other option is to first let the pie being drawn with the percentage values and replace them afterwards. To this end, one would store the autopct labels returned by plt.pie() and loop over them to replace the text with the values from the original array. Attention, plt.pie() only returns three arguments, the last one being the labels of interest, when autopct keyword is provided so we set it to an empty string here.

labels = 'Frogs', 'Hogs', 'Dogs' sizes = numpy.array([5860, 677, 3200]) colors = ['yellowgreen', 'gold', 'lightskyblue'] p, tx, autotexts = plt.pie(sizes, labels=labels, colors=colors, autopct="", shadow=True) for i, a in enumerate(autotexts): a.set_text("{}".format(sizes[i])) plt.axis('equal') plt.show()

更多推荐

本文发布于:2023-07-07 21:38:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1068509.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:图中   如何在   Python   actual   matplotlib

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!