共享坐标轴#
默认情况下,每个 Axes 都是独立缩放的。因此,如果范围不同,子图的刻度值将不对齐。
fig, (ax1, ax2) = plt.subplots(2)
fig.suptitle('Axes values are scaled individually by default')
ax1.plot(x, y)
ax2.plot(x + 1, -y)
您可以使用 sharex 或 sharey 对齐水平或垂直坐标轴。
fig, (ax1, ax2) = plt.subplots(2, sharex=True)
fig.suptitle('Aligning x-axis using sharex')
ax1.plot(x, y)
ax2.plot(x + 1, -y)
将 sharex 或 sharey 设置为 True 将在整个网格中启用全局共享,即当使用 sharey=True 时,垂直堆叠子图的 y 轴也具有相同的刻度。
fig, axs = plt.subplots(3, sharex=True, sharey=True)
fig.suptitle('Sharing both axes')
axs[0].plot(x, y ** 2)
axs[1].plot(x, 0.3 * y, 'o')
axs[2].plot(x, y, '+')
对于共享坐标轴的子图,一组刻度标签就足够了。内部 Axes 的刻度标签会被 sharex 和 sharey 自动移除。子图之间仍然存在未使用的空白区域。
为了精确控制子图的位置,可以显式使用 Figure.add_gridspec 创建一个 GridSpec,然后调用其 subplots 方法。例如,我们可以使用 add_gridspec(hspace=0) 减少垂直子图之间的高度。
label_outer 是一个方便的方法,可以移除网格边缘之外的子图的标签和刻度。
fig = plt.figure()
gs = fig.add_gridspec(3, hspace=0)
axs = gs.subplots(sharex=True, sharey=True)
fig.suptitle('Sharing both axes')
axs[0].plot(x, y ** 2)
axs[1].plot(x, 0.3 * y, 'o')
axs[2].plot(x, y, '+')
# Hide x labels and tick labels for all but bottom plot.
for ax in axs:
ax.label_outer()
除了 True 和 False 之外,sharex 和 sharey 都接受 'row' 和 'col' 值,以便仅按行或按列共享值。
fig = plt.figure()
gs = fig.add_gridspec(2, 2, hspace=0, wspace=0)
(ax1, ax2), (ax3, ax4) = gs.subplots(sharex='col', sharey='row')
fig.suptitle('Sharing x per column, y per row')
ax1.plot(x, y)
ax2.plot(x, y**2, 'tab:orange')
ax3.plot(x + 1, -y, 'tab:green')
ax4.plot(x + 2, -y**2, 'tab:red')
for ax in fig.get_axes():
ax.label_outer()
如果您需要更复杂的共享结构,您可以首先创建不共享的 Axes 网格,然后调用 axes.Axes.sharex 或 axes.Axes.sharey 以事后添加共享信息。
fig, axs = plt.subplots(2, 2)
axs[0, 0].plot(x, y)
axs[0, 0].set_title("main")
axs[1, 0].plot(x, y**2)
axs[1, 0].set_title("shares x with main")
axs[1, 0].sharex(axs[0, 0])
axs[0, 1].plot(x + 1, y + 1)
axs[0, 1].set_title("unrelated")
axs[1, 1].plot(x + 2, y + 2)
axs[1, 1].set_title("also unrelated")
fig.tight_layout()