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.
MatPlotLib with Python Create a figure using the figure() method. Using the above figure method, create the axis of the plot, using add_subplot(xyz), where x is row, y is column, and z is index. To shift the Y-axis ticks from left to right, use ax. yaxis.
To invert Y-axis, we can use invert_yaxis() method. In the above example, we import the matplotlib. pyplot and numpy library.
matplotlib.pyplot.clf() Function. The clf() function in pyplot module of matplotlib library is used to clear the current figure.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With