Rotate axis text in python matplotlib

前端 未结 13 897
暗喜
暗喜 2020-11-22 14:50

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

相关标签:
13条回答
  • 2020-11-22 15:39

    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 ) ;
    
    0 讨论(0)
  • 2020-11-22 15:43

    Appart from

    plt.xticks(rotation=90)
    

    this is also possible:

    plt.xticks(rotation='vertical')
    
    0 讨论(0)
  • This works for me:

    plt.xticks(rotation=90)
    
    0 讨论(0)
  • 2020-11-22 15:46

    If using plt:

    plt.xticks(rotation=90)
    

    In case of using pandas or seaborn to plot, assuming ax as axes for the plot:

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

    Another way of doing the above:

    for tick in ax.get_xticklabels():
        tick.set_rotation(45)
    
    0 讨论(0)
  • 2020-11-22 15:47

    To rotate the x-axis label to 90 degrees

    for tick in ax.get_xticklabels():
        tick.set_rotation(45)
    
    0 讨论(0)
  • 2020-11-22 15:48

    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)
    
    0 讨论(0)
提交回复
热议问题