Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define zorder when using 2 y-axis?

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)

enter image description here

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

like image 986
Luis Avatar asked Jul 31 '16 19:07

Luis


People also ask

What is zorder in scatter plot?

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.

What does zorder mean Matplotlib?

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.

How do I change the order of a plot in Python?

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.


2 Answers

This should work

ax1.set_zorder(ax2.get_zorder()+1)
ax1.patch.set_visible(False)
like image 168
Dan Avatar answered Sep 24 '22 04:09

Dan


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()
like image 42
Renke Avatar answered Sep 22 '22 04:09

Renke