如何在分组条形图上方显示百分比

2024-01-10

以下是 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 https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.axes.Axes.annotate.html为您的绘图添加注释。
该方法采用text注释的值和xy放置注释的坐标。

在条形图中,每个“条”由一个表示patch.Rectangle https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.patches.Rectangle.html每个矩形都有属性width, heightxy矩形左下角坐标,均可通过以下方法获取patch.get_width, patch.get_height and patch.get_xy分别。

将所有这些放在一起,解决方案是循环遍历您的每个补丁Axes,并将注释文本设置为height该补丁,具有适当的xy位于补丁中心上方的位置 - 根据其高度、宽度和 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')
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在分组条形图上方显示百分比 的相关文章

随机推荐