185

In Matplotlib, I make dashed grid lines as follows:

fig = pylab.figure()    
ax = fig.add_subplot(1,1,1)
ax.yaxis.grid(color='gray', linestyle='dashed')

however, I can't find out how (or even if it is possible) to make the grid lines be drawn behind other graph elements, such as bars. Changing the order of adding the grid versus adding other elements makes no difference.

Is it possible to make it so that the grid lines appear behind everything else?

2
  • 17
    ax.set_axisbelow(True) still works. Also nice for pdf output...
    – BandGap
    Jan 22, 2013 at 19:54
  • 12
    I would have expected ax.set_axisbelow(True) to be the default...
    – PatrickT
    Nov 25, 2018 at 12:12

7 Answers 7

178

According to this - http://matplotlib.1069221.n5.nabble.com/axis-elements-and-zorder-td5346.html - you can use Axis.set_axisbelow(True)

(I am currently installing matplotlib for the first time, so have no idea if that's correct - I just found it by googling "matplotlib z order grid" - "z order" is typically used to describe this kind of thing (z being the axis "out of the page"))

2
138

To me, it was unclear how to apply andrew cooke's answer, so this is a complete solution based on that:

ax.set_axisbelow(True)
ax.yaxis.grid(color='gray', linestyle='dashed')
1
  • Very nice, works like a charme, here! Mar 3, 2022 at 14:13
73

If you want to validate the setting for all figures, you may set

plt.rc('axes', axisbelow=True)

or

plt.rcParams['axes.axisbelow'] = True

It works for Matplotlib>=2.0.

2
  • 3
    Best answer, since people will likely want this to be consistent across all figures.
    – Constantin
    Apr 10, 2021 at 15:43
  • 2
    Make sure to put plt.grid() (or modified) after plt.rc('axes', axisbelow=True).
    – ConZZito
    Jun 28, 2022 at 8:18
8

I had the same problem and the following worked:

[line.set_zorder(3) for line in ax.lines]
fig.show() # to update

Increase 3to a higher value if it does not work.

0
4

You can also set the zorder kwarg in matplotlib.pyplot.grid

plt.grid(which='major', axis='y', zorder=-1.0)
2
  • didn't work for me Oct 5, 2021 at 7:00
  • 4
    @HomeroEsmeraldo you have to set the zorder also on everything else that gets painted. Feb 4, 2022 at 23:25
1

You can try to use one of Seaborn's styles. For instance:

import seaborn as sns  
sns.set_style("whitegrid")

Not only the gridlines will get behind but the looks are nicer.

1

For some (like me) it might be interesting to draw the grid behind only "some" of the other elements. For granular control of the draw order, you can use matplotlib.artist.Artist.set_zorder on the axes directly:

ax.yaxis.grid(color='gray', linestyle='dashed')
ax.set_zorder(3)

This is mentioned in the notes on matplotlib.axes.Axes.grid.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.