PyPlot将替代的y轴移至背景


问题内容

在pyplot中,您可以使用zorder选项或通过更改plot()命令的顺序来更改不同图形的顺序。但是,当您通过添加替代轴时ax2 = twinx(),新轴将始终覆盖旧轴(如文档所述)。

是否可以更改轴的顺序以将替代(孪生)的y轴移至背景?

在下面的示例中,我想在直方图上方显示蓝线:

import numpy as np
import matplotlib.pyplot as plt
import random

# Data
x = np.arange(-3.0, 3.01, 0.1)
y = np.power(x,2)

y2 = 1/np.sqrt(2*np.pi) * np.exp(-y/2)
data = [random.gauss(0.0, 1.0) for i in range(1000)]

# Plot figure
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax2 = ax1.twinx()

ax2.hist(data, bins=40, normed=True, color='g',zorder=0)
ax2.plot(x, y2, color='r', linewidth=2, zorder=2)
ax1.plot(x, y, color='b', linewidth=2, zorder=5)

ax1.set_ylabel("Parabola")
ax2.set_ylabel("Normal distribution")

ax1.yaxis.label.set_color('b')
ax2.yaxis.label.set_color('r')

plt.show()

编辑:由于某种原因,我无法上载此代码生成的图像。我稍后再试。


问题答案:

您可以设置zorder轴的ax.set_zorder()。然后,需要删除该轴的背景,以使下面的轴仍然可见。

ax2 = ax1.twinx()
ax1.set_zorder(10)
ax1.patch.set_visible(False)