首页 > 解决方案 > 如何命名堆叠条形图中的每个条形标签?

问题描述

我这里有一个简单的 DataFrame。我无法理解或找到标记每个条的简单方法。

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')

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)
print(totals)
y_offset = 4

我不知道如何进一步进行。我只想要“y”的总数或高度作为条形标签。

我尝试了此处提供的解决方案,但总是为每个条而不是整个条获得标签。

标签: pythonpandasmatplotlib

解决方案


一个简单的解决方案是使用plt.text

for x, y in enumerate(totals):
    if y != 0:
        plt.text(x, y, y, ha='center', va='bottom')

总计超过条形图


推荐阅读