Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
475 views
in Technique[技术] by (71.8m points)

python - PyPlot move alternative y axis to background

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).

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()

Edit: For some reason, I am unable to upload the image generated by this code. I will try again later.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...