防止双轴的网格线从原始轴绘制在艺术家之上

Prevent grid lines from twin axis to be drawn on top of artists from original axis

我有一个轴可以绘制一些数据,还有另一个双轴用于在特定刻度位置(原始轴的刻度除外)绘制网格线:

import matplotlib.pyplot as plt
import numpy as np

f, ax = plt.subplots()
ax.set_xlim([0, 1])
ax2 = ax.twiny()
ax2.set_xlim([0, 1])
ax2.set_xticks(np.linspace(0, 1, 11))
ax2.xaxis.grid()
x = np.linspace(0, 1, 100)
ax.plot(x, np.sin(x), label='sin(x)')
ax.legend()
plt.show()

现在这会产生不良影响,即双轴的网格线绘制在原始轴的图例和线图之上。据我所知,这是因为 matplotlib 按照创建的顺序绘制轴,因此 zorder 无济于事(因为 zorder 仅指定单个轴的艺术家之间的顺序) .

我知道我可以在双轴 ax2 上绘制数据(后跟 ax2.legend()),但我更愿意按原样进行设置。相反,改变绘制两个轴的顺序应该可以解决问题,但我不知道该怎么做。有 f.get_axes() 似乎 return 轴的创建顺序,但没有恢复它的选项。

或者也许还有其他解决方案?

您可以更改轴本身的 zorder。

ax.set_zorder(2)
ax2.set_zorder(1)
ax.patch.set_visible(False)