在matplotlib中的柱状图上方显示百分比

2024-05-29 03:15:38 发布

您现在位置: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([])

Dataframe

Bar Chart

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


Tags: 数据inpandasplotbarpltresultlist
1条回答
网友
1楼 · 发布于 2024-05-29 03:15:38

试试看:

colors_list = ['#5cb85c','#5bc0de','#d9534f']

# Change this line to plot percentages instead of absolute values
ax = (result.div(result.sum(1), axis=0)).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, height = p.get_width(), p.get_height()
    x, y = p.get_xy() 
    ax.annotate('{:.0%}'.format(height), (x, y + height + 0.01))

plot

相关问题 更多 >

    热门问题