The Python Oracle

Matplotlib: draw grid lines behind other graph elements

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Track title: CC G Dvoks String Quartet No 12 Ame 2

--

Chapters
00:00 Question
00:38 Accepted answer (Score 178)
01:08 Answer 2 (Score 138)
01:25 Answer 3 (Score 73)
01:47 Answer 4 (Score 8)
02:05 Thank you

--

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

Accepted answer links:
http://matplotlib.1069221.n5.nabble.com/...

--

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.