你如何在 matplotlib 中跨 twinx 控制 zorder?

How do you controle zorder across twinx in matplotlib?

我正在尝试控制 twinx 轴上不同绘图的 zorder。在 this plot 中,如何让蓝色噪声图出现在背景中,而橙色平滑图出现在前景中?

from matplotlib import pyplot as plt
import numpy as np
from  scipy.signal import savgol_filter

random = np.random.RandomState(0)
x1 = np.linspace(-10,10,500)**3 + random.normal(0, 100, size=500)
x2 = np.linspace(-10,10,500)**2 + random.normal(0, 100, size=500)

fig,ax1 = plt.subplots()
ax1.plot(x1, zorder=0)
ax1.plot(savgol_filter(x1,99,2), zorder=1)
ax2 = ax1.twinx()
ax2.plot(x2, zorder=0)
ax2.plot(savgol_filter(x2,99,2), zorder=1)
plt.show()

类似于 this thread,虽然不理想,但这是使用 twinytwinx 的方法。

# set up plots
fig, ax1 = plt.subplots()

ax2 = ax1.twinx()
ax3 = ax1.twiny()
ax4 = ax2.twiny()

# background
ax1.plot(x1)
ax2.plot(x2)

# smoothed
ax3.plot(savgol_filter(x1,99,2), c='orange')
ax4.plot(savgol_filter(x2,99,2), c='orange')

# turn off extra ticks and labels
ax3.tick_params(axis='x', which='both', bottom=False, top=False)
ax4.tick_params(axis='x', which='both', bottom=False, top=False)
ax3.set_xticklabels([])
ax4.set_xticklabels([])

# fix zorder
ax1.set_zorder(1)
ax2.set_zorder(2)
ax3.set_zorder(3)
ax4.set_zorder(4)

plt.show()

输出: