I have a bar chart and I want over each column to display some text,how can I do that ?
Asked
Active
Viewed 2.1k times
1 Answers
39
I believe this will point you in the right direction:
http://matplotlib.sourceforge.net/examples/pylab_examples/barchart_demo.html.
The part that you are most interested in is:
def autolabel(rects):
for rect in rects:
height = rect.get_height()
plt.text(rect.get_x()+rect.get_width()/2., 1.05*height, '%d'%int(height),
ha='center', va='bottom')
The placement of the text is determined by the height function, or the height of the column, and the number that is put on top of each column is written by: '%d' %int(height). So all you need to do is create an array of strings, called 'name', that you want at the top of the columns and iterate through. Be sure to change the format to be for a string (%s) and not a double.
def autolabel(rects):
# attach some text labels
for ii,rect in enumerate(rects):
height = rect.get_height()
plt.text(rect.get_x()+rect.get_width()/2., 1.02*height, '%s'% (name[ii]),
ha='center', va='bottom')
autolabel(rects1)
That should do it!

cosmosis
- 6,047
- 3
- 32
- 28
-
I have tried to understand it but I want to display a string,and this is where it troubles me.I messed with it,but I can't modify it to suit my case. – IordanouGiannis Sep 14 '11 at 22:13
-
@cosmosis The `1.02*height` doesn't really work if the y-values differ a lot (e.g., min 0 and max 1300). Any suggestions? – tobip Jul 01 '14 at 09:11
-
@ta.ft - If using a percentile doesn't work, try adding a flat number, such as `height+20`. Another solution would be to set up an if-loop within the for-loop where you designate `height1 = height * 1.02` if height < 300 but `height1 = height + 20` if height > 300. Then, in plt.text, replace the `height` call with `height1`. – cosmosis Jul 01 '14 at 16:22
-
@cosmosis That's a nice workaround but still doesn't guarantee that the distance between the bar and the text is always the same. – tobip Jul 02 '14 at 10:20
-
@ta.ft Then I suggest you just use 'height+20' or something similar if you want to guarantee that the distance will always be the same. – cosmosis Jul 02 '14 at 15:56
-
So you pass in a `plt` and yet in the function you have a predefined array of labels? Shouldn't this take in two arguments? – Dhruv Ghulati Sep 06 '16 at 17:47
-
I am also getting `height = plt.get_height() AttributeError: 'module' object has no attribute 'get_height'` – Dhruv Ghulati Sep 06 '16 at 17:48
-
1@DhruvGhulati This does not pass in a plot, it produces text above a histogram plot at a specific height where `plt` is shorthand for `import matplotlib.pyplot as plt`. The labels in the lower function do not need to be read in because they are enumerated over, along with the historgram `rects` and therefore do not need to be read in. – cosmosis Sep 06 '16 at 18:10