3

I'm plotting a series of lines on a pair of twin (twinx) axes. I can control which lines are 'on top' of each axis using the zorder parameter, and I can set which axis (as a whole) is on top using the Axes.set_zorder() function --- making all of the lines on one axis above/below all of the lines on the other axis. Is there a way to interweave the lines between the two axes?

For example, I want the upper plot (which uses a twin axis) to have the lines stacked in the same was as in the lower plot (which doesn't use a twin axis):

import numpy as np
import matplotlib.pyplot as plt

NUM_PNTS = 100
NUM_LINES = 10
scale = np.linspace(1.0,100.0,num=NUM)[::-1]

lines_left  = [ np.random.uniform(low=-scale, high=scale, size=NUM) 
                for ii in xrange(NUM_LINES) ]
lines_right = [ 50.0 + np.random.uniform(low=-scale, high=scale, size=NUM) 
                for ii in xrange(NUM_LINES) ]
fig,ax = plt.subplots(figsize=[12,12], nrows=2)
tw = ax[0].twinx()

for ll,lr in zip(lines_left,lines_right):
    ax[0].plot(ll, c='b', lw=2.0)
    tw.plot(lr, c='r', lw=2.0)

    ax[1].plot(ll, c='b', lw=2.0)
    ax[1].plot(lr, c='r', lw=2.0)

tw.set_ylim(-150,150)
for axis in ax: axis.set_ylim(-150,150)

enter image description here

I've tried setting the zorder to be interspaced, but on different axes it doesn't work, i.e.

for ii,(ll,lr) in enumerate(lines_left, lines_right):
    ax[0].plot(ll, c='b', lw=2.0, zorder=2*ii  )
    tw.plot(lr,    c='b', lw=2.0, zorder=2*ii+1)
DilithiumMatrix
  • 17,795
  • 22
  • 77
  • 119

1 Answers1

1

Axes have their own zorder as artists. From the axes documentation:

set_zorder(level) Set the zorder for the artist. Artists with lower zorder values are drawn first.

ACCEPTS: any number

It seems reasonable that zorder of children within an axes, e.g. lines, is subordinate to zorder between multiple axes. And I think your code is a demonstration that this is so.

Given your goal, you might have to renorm the y-values for the second set of data (e.g., red, here), plot them interleaved, and then add a floating spine with tick labels that describe the un-renormed y-values for the red data.

cphlewis
  • 15,759
  • 4
  • 46
  • 55