The Python Oracle

Matplotlib: draw grid lines behind other graph elements

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------

Take control of your privacy with Proton's trusted, Swiss-based, secure services.
Choose what you need and safeguard your digital life:
Mail: https://go.getproton.me/SH1CU
VPN: https://go.getproton.me/SH1DI
Password Manager: https://go.getproton.me/SH1DJ
Drive: https://go.getproton.me/SH1CT


Music by Eric Matyas
https://www.soundimage.org
Track title: Drifting Through My Dreams

--

Chapters
00:00 Matplotlib: Draw Grid Lines Behind Other Graph Elements
00:31 Accepted Answer Score 202
00:52 Answer 2 Score 9
01:04 Answer 3 Score 160
01:17 Answer 4 Score 83
01:29 Thank you

--

Full question
https://stackoverflow.com/questions/1726...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #matplotlib #grid

#avk47



ACCEPTED ANSWER

Score 202


According to this - https://web.archive.org/web/20200131000410/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"))




ANSWER 2

Score 160


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



ANSWER 3

Score 83


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.




ANSWER 4

Score 9


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.