【问题标题】:How to have actual values in matplotlib Pie Chart displayed如何在 matplotlib 饼图中显示实际值
【发布时间】:2017-04-26 13:46:51
【问题描述】:

我有一个绘制从 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)

【问题讨论】:

标签: python matplotlib graph charts pie-chart


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    如果您希望从 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)
    
    

    下面的示例创建了一个甜甜圈,但您可以尝试一下: (感谢 Kevin Amipara @https://medium.com/@kvnamipara/a-better-visualisation-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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-04
      • 2015-12-03
      • 2019-05-15
      • 1970-01-01
      相关资源
      最近更新 更多