英文:
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.
答案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')
输出结果:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论