Python 在 matplotlib 中在条形图上方显示百分比
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/52080991/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Display percentage above bar chart in matplotlib
提问by raniphore
The following are the pandas dataframe and the bar chart generated from it:
以下是 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([])
I need to display the percentages of each interest category for the respective subject above their corresponding bar. I can create a list with the percentages, but I don't understand how to add it on top of the corresponding bar.
我需要在相应栏上方显示各个主题的每个兴趣类别的百分比。我可以创建一个包含百分比的列表,但我不明白如何将它添加到相应栏的顶部。
回答by Chris A
Try this way:
试试这个方法:
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))