Z-order of the gridlines from the top axis cannot be set

Bug report

Bug summary

The gridlines from the top axis ignore the zorder and they appear on top of everything, including the plotted data and the legends. I played with setting zorders to different values. Also tried set_axisbelow(True) to no avail.

Code for reproduction

fig, ax = plt.subplots()
x = np.linspace(0,1,101)
ax.plot(x, x, 'o', label='Very linear data')
ax.legend().set_zorder(5)
axtop = ax.twiny()
ax.set_axisbelow(True)
axtop.set_axisbelow(True)
axtop.grid(zorder=-1)

Actual outcome
image

Matplotlib version

  • Operating system: Linux-4.15.0-91-generic-x86_64-with-Ubuntu-18.04-bionic
  • Matplotlib version: 3.0.3
  • Matplotlib backend: module://ipykernel.pylab.backend_inline
  • Python version: sys.version_info(major=3, minor=6, micro=9, releaselevel=’final’, serial=0)
  • Jupyter version (if applicable): Jupyter Hub 4.4.0

1 possible answer(s) on “Z-order of the gridlines from the top axis cannot be set

  1. I guess one could change the order in which the axes are created, as a work-around:

    ax.grid()
    axb = ax.twiny()
    axb.xaxis.tick_bottom()
    x = np.linspace(0,1,101)
    axb.plot(x, x, 'o', label='Very linear data')
    axb.legend()
    ax.xaxis.tick_top()
    

    Annoying, but it works.

    image