12

I am trying to rotate the x tick labels in a plot. I created a general function that plots in the style I want to plot. I do the following:

labels=ax2.get_xticklabels()
for i,label in labels:
   labels[i]=label.get_text()
ax2.set_xticklabels(labels, rotation=30)

This produced plots with no x_tick labels, so I dug deeper: I had it print the label as it was looping through and they were empty text instances. However, this is where it gets weird: When I just get the labels (labels=ax2.get_xticklabels()), and have the plot function return the list of text instances (return labels), the Text instances in the list do have the correct string, and the code above produces a list of strings as intended. I am not sure why the text instances are empty when I try to edit it inside of the function, but correct when I have the function return labels unedited. Any advice?

jjvandermade
  • 399
  • 1
  • 5
  • 13
  • 2
    Could you post a minimal working example with the code from where you are calling the function, and the error you get? – Sahil M Sep 21 '15 at 18:30

4 Answers4

31

I will answer according to the title in your question because I don't understand the explanation that follows it.

The tick labels are not populated until the figure is drawn.

plt.plot([1, 2])
ax = plt.gca()
labels = ax.get_xticklabels()
for label in labels:
    print(label)

Output:

Text(0,0,'')
Text(0,0,'')
Text(0,0,'')
Text(0,0,'')
Text(0,0,'')
Text(0,0,'')
Text(0,0,'')
Text(0,0,'')

When you call plt.draw() the tick labels are populated:

plt.plot([1, 2])
ax = plt.gca()
plt.draw()
labels = ax.get_xticklabels()
for label in labels:
    print(label)

Output:

Text(0,0,'')
Text(0,0,'0.0')
Text(0.2,0,'0.2')
Text(0.4,0,'0.4')
Text(0.6,0,'0.6')
Text(0.8,0,'0.8')
Text(1,0,'1.0')
Text(0,0,'')
Stop harming Monica
  • 12,141
  • 1
  • 36
  • 56
1

I am not sure if this is the kind of solution you wanted. I had a DataFrame whose x-ticks are all names of different cases. I had to do something like this.

ax.set_xticks(np.arange(len(my_df.index)))
ax.set_xticklabels([case for case in my_df.columns], rotation=30)
Boon
  • 56
  • 7
-1

Had the same problem,

for tl in ax2.get_xticklabels():
    tl.set_rotation(30)

works well, so I don't understand the downvotes. Since it is the same function (get_xticklabels()) and rotating through does work, drawing the labels first does not seem to be the problem at all, yet it is the most upvoted answer....

TheFlike
  • 1
  • 2
  • 1
    This is just a copy of another older answer here: https://stackoverflow.com/a/36065415/14536215 – Tzane Aug 25 '23 at 06:58
-2
for tl in ax2.get_xticklabels():
    tl.set_rotation(30)
Alex
  • 21,273
  • 10
  • 61
  • 73
Chris
  • 1
  • 1