旋转坐标轴刻度标签

573
我无法弄清楚如何在X轴上旋转文本。这是一个时间戳,随着样本数量的增加,它们越来越接近,直到重叠。我想将文本旋转90度,这样样本越靠近,它们就不会重叠。
以下是我的代码,除了我无法弄清楚如何旋转X轴文本之外,它运行得很好。
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')
13个回答

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

4
旋转 x 轴标签至 90 度。
for tick in ax.get_xticklabels():
    tick.set_rotation(45)

3
这将取决于你正在绘制什么。
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)

对于提供Axes对象的Pandas和Seaborn:

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)

如果您需要旋转标签,您可能需要更改字体大小,您可以使用 font_scale=1.0 来实现。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接