2

While there are many answers on stackoverflow for adding values to single bars, I couldn't find an appropriate way to add exact values to my grouped bars. This is how I am creating my bar chart:

labels = ['<20','20-29', '30-39','40-49','50-59','60-69','70-79','80+']
maleAges = (malesUnder20, males20To30, males30To40)
femaleAges = (femalesUnder20, females20To30,males30To40)

# bars = []

def subcategorybar(X, vals, width=0.8):
    n = len(vals)
    _X = np.arange(len(X))
    for i in range(n):
        bar = plt.bar(_X - width/2. + i/float(n)*width, vals[i], 
                width=width/float(n), align="edge")
        bars.append(bar)
    plt.xticks(_X, X)
subcategorybar(labels, [maleAges, femaleAges])

I tried using this function

def autolabel(rects):
    for rect in rects:
        height = rect.get_height()
        ax.text(rect.get_x() + rect.get_width()/2., 1.05*height,
                '%d' % int(height),
                ha='center', va='bottom')      

and passed bars from within the subcategory func but it gives me an error that

AttributeError: 'BarContainer' object has no attribute 'get_height'

An alternative way would be to use plt.text and plt.annotate but i couldn't figure out the right parameters for both, in this particular case.

Edit:

The second way I drew my chart was like this:

N = 3
labels = ['<20','20-29', '30-39','40-49']
maleAges = (malesUnder20, males20To30, males30To40)
femaleAges = (femalesUnder20, females20To30,males30To40)
ind = np.arange(N) 
width = 0.35  

plt.figure(figsize=(10,5))
plt.bar(ind, maleAges , width, label='Male')
plt.bar(ind + width, femaleAges, width, label='Female')

plt.xticks(ind + width / 2,  ('<20','20-29', '30-39'))

plt.legend(loc='best')
plt.show()

I tried using plt.annotations here as well but didn't work.

A solution with any of the two methods above could be helpful. Note: I am looking for ways to edit my existing functions.

1 Answers1

2

You could do it directly from the axes patches:

for p in axes.patches:
    axes.annotate(s=np.round(p.get_height(), decimals=2),
                xy=(p.get_x()+p.get_width()/2., p.get_height()),
                ha='center',
                va='center',
                xytext=(0, 10),
                textcoords='offset points')

Effect on your example:

import numpy as np
import matplotlib.pyplot as plt

N = 3
labels = ['<20','20-29', '30-39','40-49']
maleAges = (1, 2, 3)
femaleAges = (1, 3, 4)
ind = np.arange(N) 
width = 0.35  

figure, axes = plt.subplots()

plt.bar(ind, maleAges , width, label='Male')
plt.bar(ind + width, femaleAges, width, label='Female')

plt.xticks(ind + width / 2,  ('<20','20-29', '30-39'))

for p in axes.patches:
    axes.annotate(s=np.round(p.get_height(), decimals=2),
                xy=(p.get_x()+p.get_width()/2., p.get_height()),
                ha='center',
                va='center',
                xytext=(0, 10),
                textcoords='offset points')

plt.legend(loc='best')
plt.show()

enter image description here

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
Ynjxsjmh
  • 28,441
  • 6
  • 34
  • 52