autofmt_xdate删除所有子图的x轴标签

时间:2013-07-02 15:52:00

标签: python matplotlib

我使用autofmt_xdate以可读的方式绘制长x轴标签。问题是,当我想要组合不同的子图时,其他子图的x轴标记消失了,我不喜欢下图中最左边的子图(两行高)。有没有办法阻止autofmt_xdate淬灭其他x轴标签?或者还有另一种旋转标签的方法吗?正如您所看到的那样,我也尝试了xticks和“旋转”,但结果并不令人满意,因为标签围绕其中心旋转,导致标签混乱。

产生下图的脚本:

from matplotlib import pyplot as plt
from numpy import arange
import numpy
from matplotlib import rc

rc("figure",figsize=(15,10))
#rc('figure.subplot',bottom=0.1,hspace=0.1)
rc("legend",fontsize=16)
fig = plt.figure()


Test_Data = numpy.random.normal(size=20)

fig = plt.figure()
Dimension = (2,3)
plt.subplot2grid(Dimension, (0,0),rowspan=2)
plt.plot(Test_Data)
plt.subplot2grid(Dimension, (0,1),colspan=2)
for i,j in zip(Test_Data,arange(len(Test_Data))):
    plt.bar(i,j)
plt.legend(arange(len(Test_Data)))
plt.subplot2grid(Dimension, (1,1),colspan=2)
xticks = [r"%s (%i)" % (a,b) for a,b in zip(Test_Data,Test_Data)]
plt.xticks(arange(len(Test_Data)),xticks)
fig.autofmt_xdate()
plt.ylabel(r'$Some Latex Formula/Divided by some Latex Formula$',fontsize=14)
plt.plot(Test_Data)
#plt.setp(plt.xticks()[1],rotation=30)
plt.tight_layout()
#plt.show()

Figure created by script

1 个答案:

答案 0 :(得分:9)

这实际上是autofmt_xdate方法的一个功能。来自autofmt_xdate方法的文档:

  

日期刻度标签经常重叠,因此旋转它们并右对齐它们很有用。此外,常见的用例是具有共享xax的多个子图,其中x轴是日期数据。刻度标签通常很长,它有助于在底部子图上旋转它们并在其他子图上关闭它们,以及关闭xlabels。

如果您只想旋转右下方子图的xticklabels,请使用

plt.setp(plt.xticks()[1], rotation=30, ha='right') # ha is the same as horizontalalignment

这会将勾标标签旋转30度并将它们右对齐(与使用autofmt_xdate时的结果相同)用于右下方的子图,而另外两个子图则保持不变。