gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 02:24:41 24 4
gpt4 key购买 nike

以下是 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([])

Dataframe Bar Chart

我需要在相应栏上方显示各个主题的每个兴趣类别的百分比。我可以创建一个包含百分比的列表,但我不明白如何将它添加到相应栏的顶部。

最佳答案

尝试将以下 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 坐标。

在条形图中,每个“条形”由 patch.Rectangle 表示每个矩形都有属性widthheight和矩形左下角的xy坐标,所有这些都可以是分别通过方法patch.get_widthpatch.get_heightpatch.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')

plot

关于python - 如何在分组条形图上方显示百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52080991/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com