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

标签 python matplotlib

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

生成以下情节的脚本:

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

最佳答案

这实际上是autofmt_xdate 方法的一个特性。来自 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

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

关于python - autofmt_xdate 删除所有子图的 x 轴标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17430105/

相关文章:

python - 给定现有分布,如何绘制大小为 N 且 std 为 X 的样本?

python - 如何在 Digitalocean 上部署用 python 编写的 reddit 应用程序?

python - Matplotlib 在图中填充空白

python - matplotlib rc ('text' , usetex=True) 产生错误

python - 如何停止一秒钟并计算一秒钟内的点击次数

python - 为什么在循环中使用 sleep 时在 Python 中打印不会暂停?

python - 对 Pandas Dataframe 中的列组求和

python - 如何在 MatPlotLib (NumPy) 中绘制多维数据的轮廓?

python - 根据第三个变量改变散点图中的标记样式

python - 在 Matplotlib 中用上标或下标编写单位的最佳做法是什么?