I plot using two y-axis, on the left and the right of a matplotlib figure and use zorder
to control the position of the plots. I need to define the zorder
across axes in the same figure.
Problem
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(-10,10,0.01)
fig, ax1 = plt.subplots( 1, 1, figsize=(9,3) )
ax1.plot( x, np.sin(x), color='red', linewidth=10, zorder=1 )
ax2 = ax1.twinx()
ax2.plot( x, x, color='blue', linewidth=10, zorder=-1)
In the previous diagram, I would expect the blue line to appear behind the red plot.
How do I control the zorder
when using twin axes?
I am using:
python: 3.4.3 + numpy: 1.11.0 + matplotlib: 1.5.1
The z-order is the order of overlapping two-dimensional objects, for example, circles plotted on top of each other in a scatter plot. In CSS, there is a z-index setting that is used to bring an object forward or back within a view, controlling which object is plotted on top.
The Zorder attribute of the Matplotlib Module helps us to improve the overall representation of our plot. This property determines how close the points or plot is to the observer. The higher the value of Zorder closer the plot or points to the viewer.
You can change the order for individual artists by setting the zorder. Any individual plot() call can set a value for the zorder of that particular item. In the fist subplot below, the lines are drawn above the patch collection from the scatter, which is the default. In the subplot below, the order is reversed.
This should work
ax1.set_zorder(ax2.get_zorder()+1)
ax1.patch.set_visible(False)
the following codes works
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import ticker as tick
x = np.arange(-10,10,0.01)
plt.figure(figsize=(10, 5))
fig = plt.subplot(111)
"""be attention to here. it's fig.plot, not ax1.plot
if you write ax1.plot, then it does not work.
"""
fig.plot(x, x, color ='blue', linewidth =10)
ax2 = fig.twinx()
ax2.plot(x, np.sin(x), color='red', linewidth =10)
"""
It looks like the two axes have separate z-stacks.
The axes are z-ordered with the most recent axis on top
"""
fig.set_zorder(ax2.get_zorder()+1)
fig.patch.set_visible(False)
plt.show()
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