首页 文章

在python matplotlib中旋转轴文本

提问于
浏览
159

我无法弄清楚如何旋转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')

9 回答

  • 57

    这对我有用:

    plt.xticks(rotation=90)
    
  • 8

    Easy way

    作为described herematplotlib.pyplot figure 类中存在一个现有方法,可以根据您的需要自动旋转日期 .

    您可以在绘制数据后调用它(即 ax.plot(dates,ydata)

    fig.autofmt_xdate()
    

    如果您需要进一步格式化标签,请查看以上链接 .

    Non-datetime objects

    根据languitar的评论,我建议用于非日期时间 xticks 的方法在缩放等时不会正确更新 . 如果它不是用作x轴数据的 datetime 对象,则应遵循Tommy's answer

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

    试试pyplot.setp . 我想你可以这样做:

    x = range(len(time))
    plt.xticks(x,  time)
    locs, labels = plt.xticks()
    plt.setp(labels, rotation=90)
    plt.plot(x, delay)
    
  • 3

    公寓从

    plt.xticks(rotation=90)
    

    这也是可能的:

    plt.xticks(rotation='vertical')
    
  • 7

    我想出了一个类似的例子 . 同样,rotation关键字是..好吧,它是关键 .

    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 ) ;
    
  • 38

    我的答案受到cjohnson318答案的启发,但我不想提供硬编码的标签列表;我想旋转现有标签:

    for tick in ax.get_xticklabels():
        tick.set_rotation(45)
    
  • 28
    import pylab as pl
    pl.xticks(rotation = 90)
    
  • 36

    如果使用 plt

    plt.xticks(rotation=90)
    

    如果使用pandas或seaborn进行绘图,假设 ax 为绘图的轴:

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

    另一种做法如上:

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

    这取决于你在绘制什么 .

    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 来执行此操作 .

相关问题