python-3.x - 如何从具有不同总和数据组的数据框在条形图顶部添加百分比标签
问题描述
我是使用 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%)。恳请帮助
解决方案
在方法 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()
推荐阅读
- drop-down-menu - 升级后 Kde 应用程序菜单在 ubuntu 18.04 中不起作用
- javascript - 处理 VueJS 范围
- android - Gnirehtet VPN 已创建,但没有互联网
- php - 为什么我会收到一条聪明的通知“尝试在第 348 行获取 ...\sysplugins\smarty_internal_templatecompilerbase.php 中非对象的属性”?
- c - 我应该将一个带参数的函数分配给带 void 的函数指针吗?
- javascript - TypeError:ws.onopen 不是 stomp-node.js 中的函数
- java - 如何使 GridLayout 对所有设备通用?
- angular-router - 如果什么都没有,有没有办法在角度路由器历史记录中添加一个页面?
- java - Redirect to an url but showing a different url in the bar adress using tomcat
- python - Error in Celery: "ModuleNotFoundError: No module named 'tasks'"