Matplotlib: draw grid lines behind other chart elements

In Matplotlib, I draw dotted grid lines as follows:

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

however, I cannot find out how (or even if it is possible) to draw grid lines drawn behind other elements of the graph, such as bars. Changing the order of adding a grid and adding other elements does not matter.

Is it possible to make the grid lines appear after everything else?

+93
python matplotlib grid
Nov 13 '09 at 0:30
source share
5 answers

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 I have no idea if this is correct - I just found it using the help of "matplotlib z order grid" - "z order" is usually used to describe this kind of thing (z - axis "off page"))

+87
Nov 13 '09 at 1:13
source share

It was not clear to me how to apply the andrew cooke answer, so this is a complete solution based on this:

 ax.set_axisbelow(True) ax.yaxis.grid(color='gray', linestyle='dashed') 
+63
Aug 19 '16 at 12:51 on
source share

If you want to check the settings for all digits, you can set

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

or

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

It works for Matplotlib> = 2.0.

+21
Mar 22 '17 at 12:39 on
source share

I had the same problem and work on it worked:

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

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

+8
Mar 25 '13 at 10:09
source share

ax.grid (zorder = 0) Wood work. But first set the bar, and then the grille. Not the other way around.

 ax = df.plot.bar(x='Index', y='Values', rot=90) ax.grid(zorder=0) 

enter image description here

How to draw grid lines behind matplotlib histogram

0
Apr 29 '19 at 0:47
source share



All Articles