Home > front end >  How can I name each bar label in a stacked bar graph?
How can I name each bar label in a stacked bar graph?

Time:09-17

I have a simple DataFrame here. I am not able to understand or find easy way to label each bar.

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

I am not getting how to proceed further . I want only the totals or height of "y" as the bar label.

I tried solutions present here but always got label for each single bar and not for the whole bar.

CodePudding user response:

A simple solution is to use plt.text:

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

Total over barplot

CodePudding user response:

IIUC you want to label the bars with the total. You were almost there, I see you pre-computed the totals and defined an offset. Now you need to catch the Axes object (ax = India.plot(...)), and loop over the totals to add the texts:

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')
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)
print(totals)
y_offset = .2

for x, t in enumerate(totals):
    ax.text(x, t y_offset, t, ha='center')

Output: labeled barplot

  • Related