如何在matplotlib饼图中显示实际值(Python)?

Ant*_*nyJ 6 python charts graph matplotlib pie-chart

我有一个饼图,绘制从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)
Run Code Online (Sandbox Code Playgroud)

Imp*_*est 10

使用autopct关键字

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

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()
Run Code Online (Sandbox Code Playgroud)

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

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

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

创建饼图后更改文本

另一种选择是首先让饼图用百分比值绘制,然后替换它们.为此,可以存储由其返回的autopct标签plt.pie()并在其上循环以使用原始数组中的值替换文本.注意,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()
Run Code Online (Sandbox Code Playgroud)


mar*_*ach 6

如果您想要从 DataFrame 绘制饼图,并且想要显示实际值而不是百分比,您可以像这样重新格式化 autopct:

values=df['your_column'].value_counts(dropna=True)
plt.pie(<actual_values>, colors = colors, autopct= lambda x: '{:.0f}'.format(x*values.sum()/100), startangle=90)

Run Code Online (Sandbox Code Playgroud)

下面的示例创建了一个甜甜圈,但您可以尝试一下:(感谢 Kevin Amipara @ https://medium.com/@kvnamipara/a-better-visualization-of-pie-charts-by-matplotlib-935b7667d77f

import matplotlib.pyplot as plt

# Pie chart (plots value counts in this case)
labels = df['your_column'].dropna().unique()
actual_values = df['your_column'].value_counts(dropna=True)

#choose your colors
colors = ['#ff9999','#66b3ff','#99ff99','#ffcc99','#fffd55']
 
fig1, ax1 = plt.subplots()

# To denote actual values instead of percentages as labels in the pie chart, reformat autopct
values=df['your_column'].value_counts(dropna=True)
plt.pie(actual_values, colors = colors, autopct= lambda x: '{:.0f}'.format(x*values.sum()/100), startangle=90)


#draw circle (this example creates a donut)
centre_circle = plt.Circle((0,0),0.70,fc='white')
fig = plt.gcf()
fig.gca().add_artist(centre_circle)


# Equal aspect ratio ensures that pie is drawn as a circle
ax1.axis('equal') 

# A separate legend with labels (drawn to the bottom left of the pie in this case) 
plt.legend(labels, bbox_to_anchor = (0.1, .3))

plt.tight_layout()
plt.show()
Run Code Online (Sandbox Code Playgroud)