如何为堆叠柱状图的每根整柱添加总数标签
堆叠柱状图添加总高度标签解决方案
你已经提前计算好了每根堆叠柱的总高度totals,只需要获取柱状图的坐标轴对象,遍历每个柱子的水平位置,在对应总高度的上方添加文本标签即可,无需处理每个分段柱子。
完整可运行代码
import pandas as pd import matplotlib.pyplot as plt India = pd.DataFrame({'Year' : [1980 , 1984, 1988 , 1992, 1996 , 2000 , 2004, 2008 , 2012, 2016 , 2020] , 'Gold' : [1, 0,0,0,0,0,0,1,0,0,1], 'Silver': [0,0,0,0,0,0,1,0,2,1,2], 'Bronze' : [0,0,0,0,1,1,0,2,4,1,4] }) India = India.set_index('Year') # 承接plot方法返回的坐标轴对象,方便后续添加标签 ax = India.plot(kind='bar' , stacked = True , figsize = (8,5)) plt.xticks(rotation = 0) plt.legend(['Gold Medal','Silver Medal','Bronze Medal'] , title = "Medal Category" ) plt.title("Olympic Medal Trend - India (1980 - 2020)") plt.xlabel("Summer Olympics held(years)") plt.ylabel("Number of Medals won") totals = India.sum(axis=1) # 遍历所有柱子添加顶部总标签 for i, total in enumerate(totals): # 0.1为标签和柱子顶部的偏移量,可根据显示效果调整 ax.text(i, total + 0.1, int(total), ha='center') plt.show()
关键逻辑说明
- 堆叠柱状图的柱子默认从左到右水平坐标为
0、1、2...,和enumerate(totals)返回的索引i完全对应 ax.text参数中ha='center'保证标签和对应柱子水平居中对齐,避免出现偏移- 如果不需要显示总奖牌数为0的标签,可在循环内加判断条件
if total > 0再执行添加标签的逻辑
内容的提问来源于stack exchange,提问作者Supriya Sreedhara
相关产品推荐
相关产品推荐

