首页 > 解决方案 > 如何从具有不同总和数据组的数据框在条形图顶部添加百分比标签

问题描述

我是使用 python 编码的新手,我正在尝试开发一个顶部百分比的条形图。我有一个示例数据框 Quiz2。我开发了代码,在第一个单条上只给出了 1600%。请任何有帮助的人我怎么能正确地做到这一点?

#Approach 2
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
sns.set()
%matplotlib inline
Quiz2 = pd.DataFrame({'Kaha': ['16', '5'], 'Shiny': ['16', '10']}) 
data=Quiz2 .rename(index={0: "Male", 1: "Female"})
data=data.astype(float)
Q1p = data[['Kaha','Shiny']].plot(kind='bar',  figsize=(5, 5), legend=True, fontsize=12)
Q1p.set_xlabel("Gender", fontsize=12)
Q1p.set_ylabel("Number of people", fontsize=12)
#Q1p.set_xticklabels(x_labels)

for p in Q1p.patches:
    width = p.get_width()
    height = p.get_height()
    x, y = p.get_xy() 
    Q1p.annotate(f'{height:.0%}', (x + width/2, y + height*1.02), ha='center')
    plt.show()

我希望 Kaha 的百分比(总计 21 个)显示为(男性为 76.2%,女性为 23.8%),害羞(总计 26 个)的百分比为(男性为 61.5%,女性为 38.5%)。恳请帮助

标签: python-3.x

解决方案


在方法 2 中,您只显示 1 个值的原因是plt.show() 应该将其缩进,以便它在处理 for 循环之后出现。您将获得 1600% 的值,因为您将该值绘制为以Q1p.annotate(f'{height:.0%}'代替高度开头的行中的条形高度,这应该是高度/10*total 或为您提供百分比的东西。

这是一个解决方案,但不确定我是否正确计算了百分比:

Quiz2 = pd.DataFrame({'Kaha': ['16', '5'], 'Shiny': ['16', '10']}) 
data=Quiz2 .rename(index={0: "Male", 1: "Female"})
data=data.astype(float)
total = len(data)*10
Q1p = data[['Kaha','Shiny']].plot(kind='bar',  figsize=(5, 5), legend=True, fontsize=12)
Q1p.set_xlabel("Gender", fontsize=12)
Q1p.set_ylabel("Number of people", fontsize=12)
#Q1p.set_xticklabels(x_labels)

for p in Q1p.patches:
    width = p.get_width()
    height = p.get_height()
    x, y = p.get_xy() 
    Q1p.annotate(f'{height/total:.0%}', (x + width/2, y + height*1.02), ha='center')
plt.show()

推荐阅读