python - 如何在分组条形图上方显示百分比
问题描述
以下是 pandas 数据框和从中生成的条形图:
colors_list = ['#5cb85c','#5bc0de','#d9534f']
result.plot(kind='bar',figsize=(15,4),width = 0.8,color = colors_list,edgecolor=None)
plt.legend(labels=result.columns,fontsize= 14)
plt.title("Percentage of Respondents' Interest in Data Science Areas",fontsize= 16)
plt.xticks(fontsize=14)
for spine in plt.gca().spines.values():
spine.set_visible(False)
plt.yticks([])
我需要在相应栏上方显示各个主题的每个兴趣类别的百分比。我可以创建一个包含百分比的列表,但我不明白如何将它添加到相应栏的顶部。
解决方案
尝试将以下for
循环添加到您的代码中:
ax = result.plot(kind='bar', figsize=(15,4), width=0.8, color=colors_list, edgecolor=None)
for p in ax.patches:
width = p.get_width()
height = p.get_height()
x, y = p.get_xy()
ax.annotate(f'{height}', (x + width/2, y + height*1.02), ha='center')
解释
通常,您可以Axes.annotate
在绘图中添加注释。
此方法采用注释的text
值和xy
放置注释的坐标。
在条形图中,每个“条”由 a 表示patch.Rectangle
,每个矩形都有属性width
,height
以及xy
矩形左下角的坐标,所有这些都可以通过方法patch.get_width
,patch.get_height
和patch.get_xy
分别获得。
将所有这些放在一起,解决方案是遍历您Axes
的height
. xy
.
对于您使用百分比进行注释的特定需要,我将首先对您进行标准化DataFrame
并绘制它。
colors_list = ['#5cb85c','#5bc0de','#d9534f']
# Normalize result
result_pct = result.div(result.sum(1), axis=0)
ax = result_pct.plot(kind='bar',figsize=(15,4),width = 0.8,color = colors_list,edgecolor=None)
plt.legend(labels=result.columns,fontsize= 14)
plt.title("Percentage of Respondents' Interest in Data Science Areas",fontsize= 16)
plt.xticks(fontsize=14)
for spine in plt.gca().spines.values():
spine.set_visible(False)
plt.yticks([])
# Add this loop to add the annotations
for p in ax.patches:
width = p.get_width()
height = p.get_height()
x, y = p.get_xy()
ax.annotate(f'{height:.0%}', (x + width/2, y + height*1.02), ha='center')
推荐阅读
- node.js - 我该如何处理错误,只允许一种类型的恢复选项,但找到了多个?
- gradle - 对于 Maven 存储库凭据,buildscript 中的 Gradle 变量为空
- kubernetes - 具有两个部署的 Helm
- c++ - vtkActor2D 中的 SetWidth() 和 SetHeight() 在渲染调用后导致崩溃
- android - 透明导航栏在分屏模式下不透明
- ionic-framework - Ionic 4 - 全球 SCSS 替换“离子卡”magins?
- cython - 运算符 = 在 Cython cppclass 中
- windows - 文件夹重定向配置文件上的 %USERPROFILE%\Desktop
- jmeter - 如何在 bean shell 中验证 json 响应并执行一些操作以防响应在 jmeter 中不符合预期?
- typescript - 强制进行有区别的联合匹配