在任意子图上显示轴刻度和标签

时间:2016-03-01 13:08:29

标签: matplotlib

我有一堆四个垂直子图。如何在第三个子图下方(即第四个子图的顶部)显示x轴标签和刻度标签?这不起作用:

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots(4)
fig.subplots_adjust( hspace=0.0)  #I can't remove this. Not negotiable. :(

x = np.arange(0,10,0.1)
a = x + 1
b = np.sin(x)
c = 1.0/(1.0+x**2)

ax[0].plot( x, a )
ax[1].plot( x, b )
ax[2].plot( x, c )

for i in [0,1,2]:
    ax[i].set_xlim( [-0.2, 10.2] )

ax[2].set_xlabel( "x axis label" )
ax[2].get_xaxis().set_visible(True)
ax[3].get_xaxis().set_visible(False)

plt.show()

3 个答案:

答案 0 :(得分:1)

问题在于创建了xlabel,但是在它的顶部创建了底部子图,隐藏了它。

假设您想要保持您的子图布局完全不变,只需在底部子图的顶部显示x轴标签,您就可以更改第3个子图的zorderax[2]) ,以便它显示在其他子图上方。例如,在plt.show()

之前添加此项
ax[2].set_zorder(100)

然后您可以看到xlabelxticklabels

enter image description here

否则,你需要在轴之间创建一些空间,正如@jeanrjc在答案中所示

答案 1 :(得分:0)

问题是

fig.subplots_adjust( hspace=0.0)

线。没有它你就会得到标签。

答案 2 :(得分:0)

它确实有效。

因为你有这个:

fig.subplots_adjust( hspace=0.0)

它设置了绘图之间的高度间距,并且您不能为标签留出空间。所以,删除它

如果你不想删除它,因为你可能真正想要的是向下移动最后一根轴,那么它是可能的,只需在plt.show()之前添加:

bbox = ax[3].get_position()
ax[3].set_position([bbox.x0, bbox.y0-.075, bbox.width, bbox.height])