【问题标题】:How to annotate each segment of a stacked bar chart如何注释堆积条形图的每个部分
【发布时间】:2020-12-30 11:54:33
【问题描述】:

我一直在尝试用其值注释堆积条形图的每个子量,如上图所示(值不准确,只是一个示例)。

df.iloc[1:].T.plot(kind='bar', stacked=True)
plt.show()

我使用的数据框:

链接的帖子与我的问题有些相似,但我不理解该答案中给出的代码,也没有给出任何解释。

Annotating Values in Stacked Bar Chart Matplotlib

【问题讨论】:

    标签: python pandas matplotlib bar-chart


    【解决方案1】:

    导入和数据帧

    import pandas as pd
    import matplotlib.pyplot as plt
    
    data = {'var': ['TR', 'AC', 'F&B'], '2019 1Q': [6600, 1256, 588], '2019 2Q': [6566, 1309, 586], '2019 3Q': [7383, 1525, 673]}
    df = pd.DataFrame(data)
    df.set_index('var', inplace=True)
    
    # display(df)
         2019 1Q  2019 2Q  2019 3Q
    var                           
    TR      6600     6566     7383
    AC      1256     1309     1525
    F&B      588      586      673
    

    更新至matplotlib v3.4.2

    ax = df.T.plot.bar(stacked=True, figsize=(6, 5), rot=0)
    
    for c in ax.containers:
        ax.bar_label(c, label_type='center')
        
    ax.legend(title='Categories', bbox_to_anchor=(1.05, 1), loc='upper left')
    

    注释资源 - 来自matplotlib v3.4.2

    原始答案 - 在matplotlib v3.4.2 之前

    ax = df.T.plot.bar(stacked=True)
    plt.legend(title='Categories', bbox_to_anchor=(1.05, 1), loc='upper left')
    
    for i, rect in enumerate(ax.patches):
        # Find where everything is located
        height = rect.get_height()
        width = rect.get_width()
        x = rect.get_x()
        y = rect.get_y()
    
        # The height of the bar is the count value and can used as the label
        label_text = f'{height:.0f}'
    
        label_x = x + width / 2
        label_y = y + height / 2
    
        # don't include label if it's equivalently 0
        if height > 0.001:
            ax.text(label_x, label_y, label_text, ha='center', va='center', fontsize=8)
    

    【讨论】:

    • 使用 Matplotlib 3.4.2 更新变得更加容易。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-24
    • 1970-01-01
    • 2018-08-02
    • 2022-01-28
    • 2016-10-11
    相关资源
    最近更新 更多