I have a matplotlib bar chart and I want to add the y-values to the bars themselves. I found some stuff on the web about how to get this done, but I am having an issue. My y-values are:
2.76 3.95 6.22 7.23 9.51 10.69 11.11 11.65 11.82 12.11 13.37 14.04 15.11 15.44
But when I use the following code:
for rect in rects:
width = rect.get_x() + rect.get_width()/2.
height = rect.get_height()
plt.text(width, height/1.5,
'%d' % float(height),
ha='center', va='bottom', color='pink')
The values that appear (and they do appear, so yay!) in my bars are:
2 3 6 7 9 10 11 11 11 12 13 14 15 15
It seems that the get_height() function of matplotlib (.rectangle?) brings through an integer rather than a float, maybe? I have tried several different ways to get my full values to show, but all I ever get are the int values. How do I go about get the real values instead?
Solved! Go to Solution.
height = 1.51
'%d' % float(height)
'1'
'{: 3.2f}'.format(float(height))
' 1.51'
# --- put a variable in to make it cleaner
label = '{: 3.2f}'.format(float(height))
label
' 1.51'
put the label = line before this
plt.text(width, height/1.5, label, ha='center', va='bottom', color='pink')
And if we can rotate the text 90 degrees as well, that would be even more awesome. Of course, I need to get the first item working first, but thought I would throw that out there.
height = 1.51
'%d' % float(height)
'1'
'{: 3.2f}'.format(float(height))
' 1.51'
# --- put a variable in to make it cleaner
label = '{: 3.2f}'.format(float(height))
label
' 1.51'
put the label = line before this
plt.text(width, height/1.5, label, ha='center', va='bottom', color='pink')
PS It is useful just to examine their gallery for code snippets... seeing what you want is sometimes easier
Again, thank you so very much! You've been a life saver today.