14

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.

Julian Helfferich
  • 1,200
  • 2
  • 14
  • 29

1 Answers1

24

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)
ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
  • 7
    I like to follow this guidance http://matplotlib.1069221.n5.nabble.com/Control-twinx-series-zorder-ax2-series-behind-ax1-series-or-place-ax2-on-left-ax1-on-right-td12994.html and use `ax1.set_zorder(ax2.get_zorder()+1)` – daryl Dec 04 '17 at 19:34
  • For a question on how to plot different artists from different axes on top of each other, see [this quesiton](https://stackoverflow.com/questions/48619933/interchanging-the-zorders-on-individual-artists-from-two-axes) – ImportanceOfBeingErnest Feb 05 '18 at 13:11
  • 1
    FYI it's very important to remove the background of that axes, such that the axes below and their graphs are visible. – belka Feb 13 '19 at 09:52