在matplotlib中为堆叠条形图顶部添加注释

huangapple go评论68阅读模式
英文:

Annotating top of stacked barplot in matplotlib

问题

我在matplotlib中制作了一个堆叠条形图并希望在顶部打印每个条的总数

    import numpy as np
    import pandas as pd
    import matplotlib.pyplot as plt

    df = pd.DataFrame()
    df['year'] = ['2012','2013','2014']
    df['test 1'] = [4,17,5]
    df['test 2'] = [1,4,1]
    df['test 2a'] = [1,1,2]
    df['test 3'] = [2,1,8]
    df['test 4'] = [2,1,5]
    df['test 4a'] = [2,1,7]
    df = df.set_index('year')
    df['total'] = df.sum(axis=1)

    fig, ax = plt.subplots(1,1)
    df.drop(columns=['total']).plot(kind='bar', stacked=True, ax=ax)

    # 遍历每组容器(条)对象
    for c in ax.containers:
        # 注释容器组
        ax.bar_label(c, label_type='center')

    ##for p in ax.patches:
    ##    width, height = p.get_width(), p.get_height()
    ##    x, y = p.get_xy() 
    ##    ax.text(x+width/2, 
    ##            y+height/2, 
    ##            '{:.0f}'.format(height), 
    ##            horizontalalignment='center', 
    ##            verticalalignment='center')
英文:

I made a stacked barplot in matplotlib and want to print the total of each bar at the top,

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame()
df['year'] = ['2012','2013','2014']
df['test 1'] = [4,17,5]
df['test 2'] = [1,4,1]
df['test 2a'] = [1,1,2]
df['test 3'] = [2,1,8]
df['test 4'] = [2,1,5]
df['test 4a'] = [2,1,7]
df = df.set_index('year')
df['total'] = df.sum(axis=1)

fig, ax = plt.subplots(1,1)
df.drop(columns=['total']).plot(kind='bar', stacked=True, ax=ax)

# iterate through each group of container (bar) objects
for c in ax.containers:
    # annotate the container group
    ax.bar_label(c, label_type='center')

##for p in ax.patches:
##    width, height = p.get_width(), p.get_height()
##    x, y = p.get_xy() 
##    ax.text(x+width/2, 
##            y+height/2, 
##            '{:.0f}'.format(height), 
##            horizontalalignment='center', 
##            verticalalignment='center')

I tried using the answers in other posts, eg here and here but they print the values for every section. I'm looking for a graph like below with black text showing 12, 15, 18 values for each stacked bar. Ideally I could print the numbers in df['total'] above each stack, but I'm not sure how to do this.

在matplotlib中为堆叠条形图顶部添加注释

答案1

得分: 0

你可以在最后一个容器上简单地添加一个标签,无需使用 label_type='center'

for c in ax.containers:
    # 为每个组添加标注
    ax.bar_label(c, label_type=None)

# 为总数添加标注
ax.bar_label(ax.containers[-1], color='red')

输出结果:

在matplotlib中为堆叠条形图顶部添加注释

英文:

You can simply add a label without label_type='center' for the last conatiner:

for c in ax.containers:
    # annotates each group
    ax.bar_label(c, label_type='center')

# annotates total
ax.bar_label(ax.containers[-1], color='red')

Output:
在matplotlib中为堆叠条形图顶部添加注释

huangapple
  • 本文由 发表于 2023年2月10日 02:34:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/75403007.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定