0

I'm using matplotlib to produce a plot where I want to show labels on the right and left y-axis. You will notice by running the code that the grid-lines formed by the right-side y-axis appear on top of the plot line, where the left-side lines appear below. I would like them all to appear below the plot. I've tried zorder and set_axisbelow(True) without success.

Example code below:

import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np

t = np.linspace(0,5)
x = np.exp(-t)*np.sin(2*t)

fig, ax1 = plt.subplots()

ax1.plot(t, x)
ax2 = ax1.twinx()
ax2.plot(t, x, alpha=0.0)

ax1.set_xticks([0,1,2])
ax1.set_yticks([0.1, 0.2])
ax2.set_yticks([0.3, 0.4, 0.5])

ax1.grid(True, color='lightgray')
ax2.grid(True, color='lightgray')

for a in [ax1, ax2]:
    a.spines["top"].set_visible(False)
    a.spines["right"].set_visible(False)
    a.spines["left"].set_visible(False)
    a.spines["bottom"].set_visible(False)

ax1.set_axisbelow(True)
ax2.set_axisbelow(True)

plt.savefig('fig.pdf')
plt.show()
likethevegetable
  • 264
  • 1
  • 4
  • 17
  • 1
    Since `ax2` is above `ax1`, the gridlines of `ax2` are above any content of `ax1`. You could create 4 axes, the two lower ones for the grids and the two upper ones for the content. – ImportanceOfBeingErnest Oct 13 '19 at 01:51
  • Thanks for setting me in that direction; I was actually able to produce my desired result by setting the alpha on ax1 to 0, and using ax2 as the axes to produce the plot line. – likethevegetable Oct 13 '19 at 19:57

0 Answers0