带 delta_zorder 的双轴#

twinxtwiny 接受一个 delta_zorder 关键字参数(添加到原始坐标轴 zorder 的相对偏移量),该参数用于控制双轴是绘制在原始坐标轴的前方还是后方。

Matplotlib 还会自动管理双轴组的背景补丁(background patch)可见性,确保只有最底层的坐标轴具有可见的背景补丁(遵循 frameon 设置)。这避免了具有较高 zorder 的双轴背景遮挡住底层坐标轴上绘制的图形对象。

Twin Axes drawn behind the main Axes using delta_zorder
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 400)
y_main = np.sin(x)
y_twin = 0.4 * np.cos(x) + 0.6

fig, ax = plt.subplots()

# Put the twin Axes behind the original Axes (relative to the original zorder).
ax2 = ax.twinx(delta_zorder=-1)

# Draw something broad on the twin Axes so that the stacking is obvious.
ax2.fill_between(x, 0, y_twin, color="C1", alpha=0.35, label="twin fill")
ax2.plot(x, y_twin, color="C1", lw=6, alpha=0.8)

# Draw overlapping artists on the main Axes; they appear on top.
ax.scatter(x[::8], y_main[::8], s=35, color="C0", edgecolor="k", linewidth=0.5,
           zorder=3, label="main scatter")
ax.plot(x, y_main, color="C0", lw=4)

ax.set_xlabel("x")
ax.set_ylabel("main y")
ax2.set_ylabel("twin y")
ax.set_title("Twin Axes drawn behind the main Axes using delta_zorder")

fig.tight_layout()
plt.show()

由 Sphinx-Gallery 生成的画廊