Rotate axis text in python matplotlib

I cannot figure out how to rotate the text along the X axis. Its time stamp, as the number of samples increases, they get closer and closer until they overlap. I would like to rotate the text 90 degrees to bring samples closer, they do not overlap.

Below is what I have, it works fine, except that I cannot figure out how to rotate the text of the X axis.

import sys import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import datetime font = {'family' : 'normal', 'weight' : 'bold', 'size' : 8} matplotlib.rc('font', **font) values = open('stats.csv', 'r').readlines() time = [datetime.datetime.fromtimestamp(float(i.split(',')[0].strip())) for i in values[1:]] delay = [float(i.split(',')[1].strip()) for i in values[1:]] plt.plot(time, delay) plt.grid(b='on') plt.savefig('test.png') 
+217
python matplotlib
Jun 12 2018-12-12T00:
source share
12 answers

This works for me:

 plt.xticks(rotation=90) 
+348
Jun 08 '16 at 16:36
source share

Easy way

As described here , in the matplotlib.pyplot figure class, there is an existing method that automatically rotates the dates accordingly for you.

You can call it after you have built the data (i.e. ax.plot(dates,ydata) :

 fig.autofmt_xdate() 

If you need to format shortcuts further, check out the link above.

Objects without an object

According to the languitar comment, the method that I suggested for non-datetime xticks will not update correctly when scaling, etc. If it is not a datetime object used as data on the x axis, you should follow Tommy's answer :

 for tick in ax.get_xticklabels(): tick.set_rotation(45) 
+129
Apr 11 '14 at
source share

Try pyplot.setp. I think you could do something like this:

 x = range(len(time)) plt.xticks(x, time) locs, labels = plt.xticks() plt.setp(labels, rotation=90) plt.plot(x, delay) 
+61
Jun 12 2018-12-12T00:
source share

Appart from

 plt.xticks(rotation=90) 

it is also possible:

 plt.xticks(rotation='vertical') 
+44
01 Sep '17 at 9:38 on
source share

I came up with a similar example. Again, the rotation keyword ... well, that's the key.

 from pylab import * fig = figure() ax = fig.add_subplot(111) ax.bar( [0,1,2], [1,3,5] ) ax.set_xticks( [ 0.5, 1.5, 2.5 ] ) ax.set_xticklabels( ['tom','dick','harry'], rotation=45 ) ; 
+42
Jun 12 '12 at 14:48
source share

My answer is inspired by cjohnson318's answer, but I did not want to supply a tight list of shortcuts; I wanted to rotate existing labels:

 for tick in ax.get_xticklabels(): tick.set_rotation(45) 
+30
Sep 09 '15 at 11:45
source share

When using plt :

 plt.xticks(rotation=90) 

In the case of using pandas or the seabed for construction, considering ax as the axes for the plot:

 ax.set_xticklabels(ax.get_xticklabels(), rotation=90) 

Another way to do this:

 for tick in ax.get_xticklabels(): tick.set_rotation(45) 
+19
Mar 20 '18 at 3:09
source share

If you want to apply rotation to the axis object, the easiest way is to use tick_params . For example.

 ax.tick_params(axis='x', labelrotation=90) 

Matplotlib documentation link here .

This is useful when you have an array of axes returned by plt.subplots , and it is more convenient than using set_xticks because in this case you also need to set tick marks, and also more convenient than those that sort through ticks (for obvious reasons)

+17
Jan 24 '19 at 18:23
source share
 import pylab as pl pl.xticks(rotation = 90) 
+8
Nov 23 '16 at 17:15
source share

There are many “right” answers here, but I will add one more, because I think some details are omitted from several. The OP requested a rotation of 90 degrees, but I will change it by 45 degrees, because when you use an angle that is not zero or 90, you must also change the horizontal alignment; otherwise, your shortcuts will be off-center and a little misleading (and I assume that many people who come here want to rotate the axes by something other than 90).

The simplest / smallest code

Option 1

 plt.xticks(rotation=45, ha='right') 

As mentioned earlier, this may not be desirable if you prefer an object oriented approach.

Option 2

Another quick way (it is for date objects, but seems to work on any shortcut; I doubt this is recommended):

 fig.autofmt_xdate(rotation=45) 

fig you usually get from:

  • fig = plt.figure()
  • fig, ax = plt.subplots()
  • fig = ax.figure

Object Oriented / Work directly with ax

Option 3a

If you have a list of tags:

 labels = ['One', 'Two', 'Three'] ax.set_xticklabels(labels, rotation=45, ha='right') 

Option 3b

If you want to get a list of labels from the current chart:

 # 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') 

Option 4

Similar to the above, but instead manually crawl.

 for label in ax.get_xticklabels(): label.set_rotation(45) label.set_ha('right') 

Option 5

We still use pyplot (like plt ) here, but it is object oriented because we are changing the property of a particular ax object.

 plt.setp(ax.get_xticklabels(), rotation=45, ha='right') 

Option 6

This option is simple, but, AFAIK, you cannot set the label to align horizontally this way, so another option might be better if your angle is not 90.

 ax.tick_params(axis='x', labelrotation=45) 

Edit: There is a discussion of this exact “error”, and a fix is ​​potentially planned for v3.2.0 : https://github.com/matplotlib/matplotlib/issues/13774

+6
May 14 '19 at 10:59
source share

It will depend on what you are planning.

 import matplotlib.pyplot as plt x=['long_text_for_a_label_a', 'long_text_for_a_label_b', 'long_text_for_a_label_c'] y=[1,2,3] myplot = plt.plot(x,y) for item in myplot.axes.get_xticklabels(): item.set_rotation(90) 

For the pandas and the seabed that give you the Axes object:

 df = pd.DataFrame(x,y) #pandas myplot = df.plot.bar() #seaborn myplotsns =sns.barplot(y='0', x=df.index, data=df) # you can get xticklabels without .axes cause the object are already a # isntance of it for item in myplot.get_xticklabels(): item.set_rotation(90) 

If you need to rotate the labels, you may need to change the font size, you can use font_scale=1.0 for this.

+3
May 23 '18 at 23:00
source share

To rotate the x-axis label 90 degrees for the mark in ax.get_xticklabels (): tick.set_rotation (45)

0
Jul 10 '19 at 11:37
source share



All Articles