Matplotlib: draw grid lines behind other graph elements


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?

Asked By: Andrew



According to this – – 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”))

Answered By: andrew cooke

I had the same problem and the following worked:

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

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

Answered By: Saullo G. P. Castro

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

ax.yaxis.grid(color='gray', linestyle='dashed')
Answered By: Stefan

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

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


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

It works for Matplotlib>=2.0.

Answered By: Syrtis Major

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

import seaborn as sns  

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

Answered By: Alvaro Fuentes

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

plt.grid(which='major', axis='y', zorder=-1.0)
Answered By: Usman Tariq

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')

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

Answered By: Christian
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.