将共享轴标签放在上图

Put shared axis labels to upper plot

from matplotlib import pyplot as plt
fig, (ax0, ax1) = plt.subplots(nrows=2, sharex=True)
fig.show()

Returns这个数字:

但我想要第一个图下方的 x 轴标签,而不是第二个图下方,如下所示。我怎样才能做到这一点?

official reference里面有一个例子,所以我参考它回答了:在tick参数中,将bottom label设置为false。

import matplotlib.pyplot as plt

ax0 = plt.subplot(211)
ax1 = plt.subplot(212, sharex=ax0, sharey=ax0)
#plt.plot([],[])
plt.tick_params('x', labelbottom=False)
#print(ax1.get_xticks())

plt.show()

@r-beginners 的回答让我找到了一个解决方案,该解决方案在使用 plt.subplots 快捷方式而不是分别实例化每个轴时也有效。

from matplotlib import pyplot as plt
fig, (ax0, ax1) = plt.subplots(nrows=2, sharex=True)
plt.tick_params('x', labelbottom=False, labeltop=True)
fig.show()

他的基本部分是 plt.tick_params,它采用关键字参数 labeltoplabelbottom(以及 labelleftlabelright 用于多个列上的共享轴) 到 select / deselect 每个轴单独。