matplotlib, need float rather than int

453
4
Jump to solution
04-26-2018 08:17 AM
ChrissyWhite
New Contributor III

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?

0 Kudos
1 Solution

Accepted Solutions
DanPatterson_Retired
MVP Esteemed Contributor
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')

View solution in original post

4 Replies
ChrissyWhite
New Contributor III

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.

0 Kudos
DanPatterson_Retired
MVP Esteemed Contributor
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')

DanPatterson_Retired
MVP Esteemed Contributor

PS   It is useful just to examine their gallery for code snippets... seeing what you want is sometimes easier

https://matplotlib.org/gallery/index.html

ChrissyWhite
New Contributor III

Again, thank you so very much! You've been a life saver today.

0 Kudos