Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib: draw grid lines behind other graph elements

People also ask

How do I show a minor grid in Matplotlib?

Matplotlib doesn't show the minor ticks / grid by default so you also need explicitly show them using minorticks_on() .

What is Matplotlib Zorder?

The Zorder attribute of the Matplotlib Module helps us to improve the overall representation of our plot. This property determines how close the points or plot is to the observer. The higher the value of Zorder closer the plot or points to the viewer.


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


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

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.


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.


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.