我有以下数据集,并且我使用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)
我需要在图表中注释值。例如,我需要每个条形的值显示在图形的条形图内。见下面的例子
答案 0 :(得分:2)
使用以下代码:
# 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')