【问题标题】:Stacked bars are unexpectedly annotated with the sum of bar heights堆叠的条形图意外地用条形高度的总和进行了注释
【发布时间】:2022-01-13 04:33:00
【问题描述】:

我的数据:

names_col = ['Count','Freq']
dat = [['Matching', 56935],['Mismatching', 100587]]
plot_df = pd.DataFrame(data=dat,columns=names_col)

我尝试绘制带有显示值的堆叠 catplot,这是我的代码:

plt.figure(figsize=(16,9))
p=plot_df.set_index('Count').T.plot(kind='bar', stacked=True)
p.bar_label(p.containers[0])
p.bar_label(p.containers[1])
plt.show();

首先,输出的数字不是大小(16,9),有什么问题? 第二个图显示值为:

取而代之的是matching - 56935(这里没问题)和mismatching - 100587 的值,绘图显示总数(157522)。 我如何访问和显示Mismatching 值?

【问题讨论】:

    标签: python pandas matplotlib annotations bar-chart


    【解决方案1】:
    • 使用matplotlib.pyplot.bar_label 两次
      • 根据标签是在条的中心还是条的边缘来确定注释值。
      • 另一个答案使用x[0].,因为只有一组堆叠条形,但如果 x 轴上有多个组,这将不起作用。
      • 请参阅此answer 了解更多详细信息和.bar_label 的示例。
    • 重塑数据框应该是一个独立于绘图的步骤
    • pandas.DataFrame.plot 使用matplotlib 作为默认的绘图后端,并具有许多参数,如rotxlabelylabelfigsize,用于自定义绘图。
    • python 3.10pandas 1.3.4matplotlib 3.5.0 中测试
    df = pd.DataFrame(data=dat, columns=names_col)
    dft = df.set_index('Count').T
    
    axe = dft.plot(kind='bar', stacked=True, figsize=(16,9), rot=0)
    
    for x in axe.containers:
        axe.bar_label(x, label_type='edge', weight='bold')
        axe.bar_label(x, label_type='center', weight='bold', color='white')
    

    • 这是一个包含多个组的更全面的示例
      • 另一个答案没有为第二组条放置中间注释。
    # test data 
    data = {'Matching': [56935, 17610], 'Mismatching': [100587, 13794], 'Test': [33139, 23567]}
    df = pd.DataFrame(data=data, index=['Freq', 'Freq2'])
    
    axe = df.plot(kind='bar', stacked=True, figsize=(16,9), rot=0)
    
    for x in axe.containers:
        axe.bar_label(x, label_type='edge', weight='bold')
        axe.bar_label(x, label_type='center', weight='bold', color='white')
    

    【讨论】:

    • "注释值是根据标签是在条的中心还是条的边缘来确定的"。不知道!确实干净多了!
    • @Tranbi 我也没有。当我发现那个“功能”时,我正在设置注释。
    【解决方案2】:

    您可以将figsize 设置为绘图参数。然后为每个容器添加条形标签和您自己的文本:

    p=plot_df.set_index('Count').T.plot(kind='bar', stacked=True, figsize=(16,9)) 
    for x in p.containers:
        p.bar_label(x)
        p.text(0, x[0].get_y() + x[0].get_height()*0.5, x.datavalues[0], ha='center', color='w', weight='bold')
    
    plt.show()
    

    输出:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-10
      • 2018-09-30
      • 2023-01-21
      相关资源
      最近更新 更多