Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python matplotlib bar chart adding bar titles

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!

like image 993
thebeancounter Avatar asked Oct 27 '16 14:10

thebeancounter


People also ask

How do I add a title to my PLT bar?

To set title for plot in matplotlib, call title() function on the matplotlib. pyplot object and pass required title name as argument for the title() function. The following code snippet sets the title of the plot to “Sample Title”.

How do you add labels to a bar graph?

Add data labelsClick the chart, and then click the Chart Design tab. Click Add Chart Element and select Data Labels, and then select a location for the data label option. Note: The options will differ depending on your chart type.


1 Answers

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

like image 113
DavidG Avatar answered Oct 11 '22 16:10

DavidG