xticklabels旋转后消失

时间:2016-04-05 18:43:29

标签: python matplotlib

我正在网格上绘制几个数据集。时间序列延续了一年的时间,因此我希望有一个月份刻度标记,但刻度标签很快会相互重叠。为了解决这个问题,我尝试旋转xticklables。但是,这没有按预期工作。这是一个非最小的工作示例:

from __future__ import division, print_function

import pandas as pd, numpy as np
from pylab import *

index = pd.date_range('20140901','20150901',freq='1H')
data  = np.sin( np.pi*np.arange(index.shape[0])/180 )
df = pd.DataFrame(index=index,data=data,columns=list("A"))

fig = figure( figsize=(3.25,4.0) )
gs  = GridSpec(5,2)
gs.update(left=0.08, right=0.925, top=0.95, bottom=0.05, hspace=0.0, wspace=0.0)

ax0 = subplot(gs[0])
ax1 = subplot(gs[1])
ax2 = subplot(gs[2])
ax3 = subplot(gs[3])
ax4 = subplot(gs[4])
ax5 = subplot(gs[5])
ax6 = subplot(gs[6])
ax7 = subplot(gs[7])

for axis in xrange(8):
    ax = eval('ax'+str(axis))

    ax.plot(df.index,df.A,'k')

    # format y-axes
    if axis in np.arange(1,8,2):
        ax.set_yticks(np.arange(-1.5,1.5,0.50),minor=False)
        ax.set_yticks(np.arange(-1.5,1.5,0.25),minor=True)
        ax.set_yticklabels([])

    elif axis in np.arange(2,8,2):
        ax.set_yticks(np.arange(-1.5,1.5,0.50),minor=False)
        ax.set_yticks(np.arange(-1.5,1.5,0.25),minor=True)

    elif axis==0:
        ax.set_yticks(np.arange(-1.5,1.6,0.50),minor=False)
        ax.set_yticks(np.arange(-1.5,1.5,0.25),minor=True)

    ax.set_ylim([-1.5,1.5])

    # format x-axes
    if axis in np.arange(0,6):
        ax.set_xticklabels([])
        ax.xaxis.set_minor_locator(dates.MonthLocator(interval=1))
        ax.xaxis.set_major_locator(dates.MonthLocator(interval=3))

    elif axis in [6,7]:
        ax.xaxis.set_minor_locator(dates.MonthLocator(interval=1))
        ax.xaxis.set_major_locator(dates.MonthLocator(interval=3))
        ax.xaxis.set_major_formatter(dates.DateFormatter('%b-%Y'))

    ax.set_xlim([dt.datetime(2014,9,1),dt.datetime(2015,9,1)])

    ax.tick_params(axis='both',which='major',direction='in',length=4,width=1,labelsize=8)
    ax.tick_params(axis='both',which='minor',direction='in',length=2,width=1)    


    # insert text boxes
    ax.annotate('A', 
                xycoords='axes fraction',
                xy=(0.05,0.75), 
                horizontalalignment='left',
                verticalalignment='bottom',
                fontsize=8)

ax6.set_xticklabels(ax6.get_xticklabels(),rotation=45)
ax7.set_xticklabels(ax7.get_xticklabels(),rotation=45)

如果我按原样运行脚本,最下面的x轴上将没有ticklabels。但是,如果我注释掉最后两行,则运行脚本,然后手动输入最后两行,按预期完成旋转。我已经研究了几种旋转刻度标签的方法,其中没有一种工作(即它们都具有相同的“消失”问题)。有谁知道为什么会这样,以及如何解决它?

Python 2.7,Matplotlib 1.5.1,Pandas 0.18.0

enter image description here enter image description here

1 个答案:

答案 0 :(得分:1)

像这样更改你的程序会有效。

# format x-axes
if axis in np.arange(0,6):
    ax.set_xticklabels([])
    ax.xaxis.set_minor_locator(dates.MonthLocator(interval=1))
    ax.xaxis.set_major_locator(dates.MonthLocator(interval=3))

elif axis in [6,7]:
    ax.set_xticklabels(index.strftime('%b-%Y'),rotation=45)      # Add this line
    ax.xaxis.set_minor_locator(dates.MonthLocator(interval=1))
    ax.xaxis.set_major_locator(dates.MonthLocator(interval=3))
    # ax.xaxis.set_major_formatter(dates.DateFormatter('%b-%Y')) # This not needed