【问题标题】:Total label for stacked bar [duplicate]堆叠条的总标签 [重复]
【发布时间】:2022-01-23 14:01:14
【问题描述】:

我有以下代码:

fig, ax = plt.subplots()
single_customer_g['Size_GB'] = round(single_customer_g['Size_GB'] / 1024, 2)
single_customer_g = single_customer_g.pivot('Date', 'Vault', 'Size_GB')
single_customer_g.plot.bar(stacked=True, rot=1, figsize=(15, 10), ax=ax, zorder=3)

for c in ax.containers:
    labels = [round(v.get_height(), 2) if v.get_height() > 0 else 0 for v in c]
    ax.bar_label(c, labels=labels, label_type='center')

我正在尝试在每列顶部添加总数字作为标签,但无法弄清楚。我尝试了多个示例,但到目前为止没有任何效果。

【问题讨论】:

    标签: python pandas matplotlib


    【解决方案1】:

    默认情况下,函数bar_label() 使用条形高度及其底部的总和 (.get_y()) 作为顶部显示的数字(仅居中标签的高度)。您只想为显示的最后一组条形图调用它(所以ax.containers[-1])。

    这是一个例子:

    from matplotlib import pyplot as plt
    import pandas as pd
    import numpy as np
    
    df = pd.DataFrame({'Date': np.tile(pd.date_range('20211201', freq='D', periods=10), 5),
                       'Vault': np.repeat([*'abcde'], 10),
                       'Size_GB': np.random.uniform(0, 3, 50)})
    df_pivoted = df.pivot('Date', 'Vault', 'Size_GB')
    ax = df_pivoted.plot.bar(stacked=True, figsize=(12, 5))
    ax.set_xticklabels([d.strftime('%b %d\n%Y') for d in df_pivoted.index], rotation=0)
    ax.bar_label(ax.containers[-1], fmt='%.2f') # default on top
    for bars in ax.containers:
        labels = [f"{bar.get_height():.2f}" if bar.get_height() > 0.2 else '' for bar in bars]
        ax.bar_label(bars, labels=labels, label_type='center', color='white')
    ax.set_xlabel('')
    plt.tight_layout()
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-28
      相关资源
      最近更新 更多