Matplotlib: draw grid lines behind other graph elements
Asked Answered
S

10

205

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?

Sagacious answered 13/11, 2009 at 0:30 Comment(2)
ax.set_axisbelow(True) still works. Also nice for pdf output...Comber
I would have expected ax.set_axisbelow(True) to be the default...Egocentrism
E
197

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

Evelynneven answered 13/11, 2009 at 1:13 Comment(2)
Is it possible to have the gridlines below the bar/line while retaining the labels on top? I also posted this quesiton separately #29522947Tripalmitin
It might be this matplotlib.1069221.n5.nabble.com/…, ancient thread though.Ermines
G
154

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')
Gley answered 19/8, 2016 at 12:51 Comment(2)
Very nice, works like a charme, here!Flapdoodle
As of June 2023 this is the only answer that has worked for me. Setting zorders to 0 or even negative for the grid and high for the plot element hasn't worked.Batchelor
K
79

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.

Klemens answered 22/3, 2017 at 12:39 Comment(2)
Best answer, since people will likely want this to be consistent across all figures.Yukikoyukio
Make sure to put plt.grid() (or modified) after plt.rc('axes', axisbelow=True).Maryammaryann
S
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.

Stool answered 25/3, 2013 at 10:9 Comment(0)
A
7

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

plt.grid(which='major', axis='y', zorder=-1.0)
Anaesthetize answered 25/8, 2021 at 18:4 Comment(2)
didn't work for meWomanizer
@HomeroEsmeraldo you have to set the zorder also on everything else that gets painted.Weever
M
3

Just make sure the points have a higher zorder value than the gridlines, e.g.:

plt.scatter(x,y,c="k",marker="x",zorder=2)

followed by

plt.grid(linestyle="--",alpha=0.5,zorder=1)
Merchantman answered 2/8, 2023 at 10:44 Comment(0)
Y
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.

Yemane answered 16/2, 2021 at 16:29 Comment(0)
R
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.

Roberts answered 27/11, 2021 at 14:39 Comment(0)
U
0

These answers weren't working for me (zorder, axisbelow, set_zorder):

fig, ax = plt.subplots(3, 1, dpi=200)
ax[0].yaxis.grid(True, which='major', linestyle='--')
ax[0].boxplot(data, positions=[0, 0.5], widths=[0.5, 0.5])

Instead, changing the background color of the graph elements using patch_artist worked for me:

l = ax[0].boxplot(data, positions=[0, 0.5], widths=[0.5, 0.5],
  patch_artist=True)
for bplot in (l,):
  for patch, color in zip(bplot['boxes'], ['white', 'white']):
    patch.set_facecolor(color)
``
Unmerciful answered 6/8, 2023 at 1:14 Comment(0)
P
0

ax.grid(color='grey', alpha=0.2)

set the transparency of gridlines to low using alpha=0.2 this might make the gridlines appear behind the actual graph

Perri answered 22/1 at 16:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.