Rotate axis text in python matplotlib

匿名 (未验证) 提交于 2019-12-03 02:00:02

问题:

I can't figure out how to rotate the text on the X Axis. Its a time stamp, so as the number of samples increase, they get closer and closer until they overlap. I'd like to rotate the text 90 degrees so as the samples get closer together, they aren't overlapping.

Below is what I have, it works fine with the exception that I can't figure out how to rotate the X axis text.

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

回答1:

This works for me:

plt.xticks(rotation=90) 


回答2:

Easy way

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

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

fig.autofmt_xdate() 

If you need to format the labels further, checkout the above link.

Non-datetime objects

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) 


回答3:

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) 


回答4:

I came up with a similar example. Again, the rotation keyword is.. well, it's 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 ) ; 


回答5:

Appart from

plt.xticks(rotation=90) 

this is also possible:

plt.xticks(rotation='vertical') 


回答6:

My answer is inspired by cjohnson318's answer, but I didn't want to supply a hardcoded list of labels; I wanted to rotate the existing labels:

for tick in ax.get_xticklabels():     tick.set_rotation(45) 


回答7:

import pylab as pl pl.xticks(rotation = 90) 


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!