0

I am getting a ValueError: could not convert string to float when converting tick label values into numeric types.

According to the Text documentation though, a string should be returned.

MVP

fig, ax = plt.subplots()
ax.plot( range( 5 ), range( 5 ) )

for lbl in ax.get_xticklabels():
    float( lbl.get_text() )
bicarlsen
  • 1,241
  • 10
  • 27
  • if you do `print(lbl.get_text())` what is the output? – Carlos Gonzalez Apr 12 '19 at 09:09
  • It seems to be the string, e.g. -0.5 – bicarlsen Apr 12 '19 at 09:10
  • Is it possible something strange is going on with the Formatter? – bicarlsen Apr 12 '19 at 09:11
  • when I use you code and change `float( lbl.get_text() )` to`print(float(lbl.get_text())` I get empty strings which can not be converted to string – Carlos Gonzalez Apr 12 '19 at 09:14
  • If I before the for loop you put `plt.show()` then curiosly enough I get the expected output your problem is explained in one of the answers here https://stackoverflow.com/questions/32700935/get-xticklabels-contains-empty-text-instances bascally until you dont call `plt.show()` the xticks are not populated – Carlos Gonzalez Apr 12 '19 at 09:16
  • Amazing! Thanks for the help, that was the issue. In my actual case I think there was a hangover during the print statements because I was looping over some subplots. – bicarlsen Apr 12 '19 at 09:27
  • @CarlosGonzalez If you want to post an answer I'd definitely accept it. – bicarlsen Apr 12 '19 at 09:28

1 Answers1

0

Your current code gets the xtixk labels before being populated so if you do

fig, ax = plt.subplots()
ax.plot( range( 5 ), range( 5 ) )

for lbl in ax.get_xticklabels():
    print(lbl.get_text())

You will see that all the labels are empty strings. If you put plt.show() before the for loop it should populate the list and you should be able to get the labels.

Carlos Gonzalez
  • 858
  • 13
  • 23