在堆积的条形图Matplotlib中注释值 [英] Annotating Values in Stacked Bar Chart Matplotlib
本文介绍了在堆积的条形图Matplotlib中注释值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下数据集,并已使用Matplotlib绘制了堆积条形图.
I have the following dataset and I have plotted a Stacked Bar Chart using Matplotlib.
industry Distribution Manufacturing Retail Services
2017-09 1 4 12 7
2017-10 3 2 3 4
2017-11 1 0 2 1
2018-02 1 0 0 0
以下是生成图的代码:
fig, ax = plt.subplots(1, figsize=(17,6))
part1 = ax.bar(industry_split.index.values, 'Retail', data=industry_split, color = 'darkblue', width=0.5, edgecolor=edgecolor, linewidth=linewidth)
part2 = ax.bar(industry_split.index.values, 'Services', data=industry_split, color = 'dodgerblue', edgecolor=edgecolor, linewidth=linewidth, width=0.5, bottom = industry_split.Retail)
part3 = ax.bar(industry_split.index.values, 'Manufacturing', data=industry_split, color = 'green', width=0.5, edgecolor=edgecolor, linewidth=linewidth, bottom = industry_split.Retail + industry_split.Services)
part4 = ax.bar(industry_split.index.values, 'Distribution', data=industry_split, color = 'orange', width=0.5, edgecolor=edgecolor, linewidth=linewidth, bottom = industry_split.Retail + industry_split.Services + industry_split.Manufacturing)
我需要注释图形中的值.例如,我需要每个条形的值都显示在图形的条形内部.参见下面的示例
I need to annotate the values in the graph. For instance, I need the value for each bar to appear inside the bar of the graph. See example below
推荐答案
使用以下代码:
# Adding Data Labels
for i, label in enumerate(list(industry_split.index.values)):
score1 = industry_split.loc[label]['Retail']
if score1 == 0:
None
else:
ax.annotate(str(score1), (i, score1 - 0.7), color='white', fontsize=12, weight='semibold')
score2 = industry_split.loc[label]['Services']
if score2 == 0:
None
else:
ax.annotate(str(score2), (i, score1 + score2 - 0.7), color='white', fontsize=12, weight='semibold')
score3 = industry_split.loc[label]['Manufacturing']
if score3 == 0:
None
else:
ax.annotate(str(score3), (i, score1 + score2 + score3 - 0.7), color='white', fontsize=12, weight='semibold')
score4 = industry_split.loc[label]['Distribution']
if score4 == 0:
None
else:
ax.annotate(str(score4), (i, score1 + score2 + score3 + score4 - 0.7), color='white', fontsize=12, weight='semibold')
这篇关于在堆积的条形图Matplotlib中注释值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文