Rotate axis text in python matplotlib
As described here, there is an existing method in the
figure class that automatically rotates dates appropriately for you figure.
You can call it after you plot your data (i.e.
If you need to format the labels further, checkout the above link.
As per languitar's comment, the method I suggested for non-datetime
xticks would not update correctly when zooming, etc. If it's not a
datetime object used as your x-axis data, you should follow Tommy's answer:
for tick in ax.get_xticklabels(): tick.set_rotation(45)
Many "correct" answers here but I'll add one more since I think some details are left out of several. The OP asked for 90 degree rotation but I'll change to 45 degrees because when you use an angle that isn't zero or 90, you should change the horizontal alignment as well; otherwise your labels will be off-center and a bit misleading (and I'm guessing many people who come here want to rotate axes to something other than 90).
Easiest / Least Code
As mentioned previously, that may not be desirable if you'd rather take the Object Oriented approach.
Another fast way (it's intended for date objects but seems to work on any label; doubt this is recommended though):
fig you would usually get from:
fig = plt.gcf()
fig = plt.figure()
fig, ax = plt.subplots()
fig = ax.figure
Object-Oriented / Dealing directly with
If you have the list of labels:
labels = ['One', 'Two', 'Three']ax.set_xticklabels(labels, rotation=45, ha='right')
If you want to get the list of labels from the current plot:
# Unfortunately you need to draw your figure first to assign the labels,# otherwise get_xticklabels() will return empty strings.plt.draw()ax.set_xticklabels(ax.get_xticklabels(), rotation=45, ha='right')
Similar to above, but loop through manually instead.
for label in ax.get_xticklabels(): label.set_rotation(45) label.set_ha('right')
We still use
plt) here but it's object-oriented because we're changing the property of a specific
plt.setp(ax.get_xticklabels(), rotation=45, ha='right')
This option is simple, but AFAIK you can't set label horizontal align this way so another option might be better if your angle is not 90.
Edit:There's discussion of this exact "bug" but a fix hasn't been released (as of