You cannot simply adjust the z-order of artists across axes. The z-order of the Artists belonging to one Axes
are relative to that axes only.
You can, however, obtain the desired effect, but no easily. Here are two options:
Using 3 axes
The simplest way in my opinion is to use 3 axes, with the 3rd axis being a complete "clone" of the first one, but with a z-order above ax2
.
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax3 = fig.add_axes(ax1.get_position(), sharex=ax1, sharey=ax1)
ax3.set_facecolor('none') #prevents axes background from hiding artists below
ax3.set_axis_off() # pervents superimposed ticks from being drawn
l_bottom, = ax1.plot([1,2,3], [4,6,6], lw=10, c='C1')
l2, = ax2.plot([1,2,3], [60,30,40], lw=10, c='C2')
l_top, = ax3.plot([1,2,3],[5,10,3], lw=10, c='C3')
ax3.legend([l_bottom, l2, l_top],['left','right','left'])
ax3.set_title('using a 3rd axe')
Using transforms
This methods only uses 2 axes, but plots the green line on ax2
using the data-coordinates from ax1
. The problem with that method is that ax1 will not autoscale automatically, hence the need to call set_ylim()
. Plus it could get quite confusing in a larger code to keep track of which transform is used by which artist.
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
l_bottom, = ax1.plot([1,2,3], [4,6,6], lw=10, c='C1')
l2, = ax2.plot([1,2,3], [60,30,40], lw=10, c='C2')
l_top, = ax2.plot([1,2,3],[5,10,3], lw=10, c='C3',transform=ax1.transData)
ax1.set_ylim(2.65,10.35) # matches the limits on the previous graph
ax2.set_ylim(28.5,61.5)
ax2.legend([l_bottom, l2, l_top],['left','right','left'])
ax2.set_title('using transforms')