autofmt_xdate删除所有子批次的x轴标签

2024-06-26 00:24:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用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


Tags: fromtestimportnumpydataplt标签子块
1条回答
网友
1楼 · 发布于 2024-06-26 00:24:49

这实际上是autofmt_xdate方法的一个特性。从^{}方法的文档中:

Date ticklabels often overlap, so it is useful to rotate them and right align them. Also, a common use case is a number of subplots with shared xaxes where the x-axis is date data. The ticklabels are often long, and it helps to rotate them on the bottom subplot and turn them off on other subplots, as well as turn off xlabels.

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

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

这会将ticklebels旋转30度并将其右对齐(与使用autofmt_xdate时的结果相同),保留其他两个子块不变。

相关问题 更多 >