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

问题描述

我正在尝试控制 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,500)**2 + random.normal(0,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,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,c='orange')

# turn off extra ticks and labels
ax3.tick_params(axis='x',which='both',bottom=False,top=False)
ax4.tick_params(axis='x',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()

输出:

enter image description here

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...