11

I am using matplotlib with python 2.7

I need to create a simple pyplot bar chart, and for every bar, I need to add, on top of it, the y value of it.

I am creating a bar chart with the following code:

import matplotlib.pyplot as plt

barlist = plt.bar([0,1,2,3], [100,200,300,400], width=5)

barlist[0].set_color('r')
barlist[0].title("what?!")

the changing of color works, but for the title i get the following error: AttributeError: 'Rectangle' object has no attribute 'title'

i found some questions about similar question but they are not using the same way of creating a bar chart, and their solution did not work for me.

any ideas for a simple solution for adding the values of the bars as titles above them?

thanks!

Community
  • 1
  • 1
thebeancounter
  • 4,261
  • 8
  • 61
  • 109

2 Answers2

11

The matplotlib.pyplot.bar documentation can be found here. There is an example form the documentation which can be found here which illustrates how to plot a bar chart with labels above the bars. It can be modified slightly to use the sample data in your question:

from __future__ import division
import matplotlib.pyplot as plt
import numpy as np

x = [0,1,2,3]
freq = [100,200,300,400]
width = 0.8 # width of the bars

fig, ax = plt.subplots()
rects1 = ax.bar(x, freq, width, color='r')

ax.set_ylim(0,450)
ax.set_ylabel('Frequency')
ax.set_title('Insert Title Here')
ax.set_xticks(np.add(x,(width/2))) # set the position of the x ticks
ax.set_xticklabels(('X1', 'X2', 'X3', 'X4', 'X5'))

def autolabel(rects):
    # attach some text labels
    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')

autolabel(rects1)

plt.show()

This produces the following graph:

enter image description here

DavidG
  • 24,279
  • 14
  • 89
  • 82
3

As of matplotlib 3.4.0, you can use the built-in plt.bar_label helper method to auto-label the bars.

Supply containers[0] from the current axes:

plt.bar([0,1,2,3], [100,200,300,400])
ax = plt.gca()
plt.bar_label(ax.containers[0])

Or if you have grouped bars, iterate containers:

for container in ax.containers:
    plt.bar_label(container)

plt.bar with plt.bar_label

tdy
  • 36,675
  • 19
  • 86
  • 83