PyPlot将替代的y轴移至背景 [英] PyPlot move alternative y axis to background
问题描述
在pyplot中,可以使用zorder
选项或通过更改plot()
命令的顺序来更改不同图形的顺序.但是,当您通过ax2 = twinx()
添加备用轴时,新轴将始终覆盖旧轴(如
In pyplot, you can change the order of different graphs using the zorder
option or by changing the order of the plot()
commands. However, when you add an alternative axis via ax2 = twinx()
, the new axis will always overlay the old axis (as described in the documentation).
是否可以更改轴的顺序以将替代(孪生)的y轴移至背景?
Is it possible to change the order of the axis to move the alternative (twinned) y-axis to background?
在下面的示例中,我想在直方图的顶部显示蓝线:
In the example below, I would like to display the blue line on top of the histogram:
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()
由于某种原因,我无法上载此代码生成的图像.我待会再试.
For some reason, I am unable to upload the image generated by this code. I will try again later.
推荐答案
您可以设置轴的zorder
,ax.set_zorder()
.然后,需要删除该轴的背景,以使下面的轴仍然可见.
You can set the zorder
of an axes, ax.set_zorder()
. One would then need to remove the background of that axes, such that the axes below is still visible.
ax2 = ax1.twinx()
ax1.set_zorder(10)
ax1.patch.set_visible(False)
这篇关于PyPlot将替代的y轴移至背景的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!