python - 在堆积条形图中注释值 Matplotlib

标签 python matplotlib graph annotate

我有以下数据集,并使用 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)

enter image description here

我需要注释图表中的值。例如,我需要每个条形的值显示在图表的条形内部。请参阅下面的示例

enter image description here

最佳答案

使用以下代码:

# 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')

关于python - 在堆积条形图中注释值 Matplotlib,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48922328/

相关文章:

java - 使用福特 - Fulkerson 输出路径

python - str.translate 与 str.replace - 何时使用哪一个?

python - str 对象不可调用 (sqlite3)

python - groupby 在多索引级别上并删除分组级别

python - Pyparsing:如何将 token 存储到以下列表/组中?

javascript - 如何更改 Google Chart 中的 X 指标?

python - 如何避免 matplotlib 中重叠的误差线?

python - 如何用渐变填充 matplotlib 条形图?

python - 如何从数据框中绘制表面图/3d 图

graph - 参数映射不能在 MERGE 模式中使用