Reputation: 1695
I am trying to draw a grid using matplotlib. The zorder of the grid should be behind all other lines in the plot. My problem so far is that the minor grid lines are always drawn in front of the major grid lines i.e.
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import MultipleLocator, FormatStrFormatter
plt.rc('text', usetex=True)
plt.rc('font', family='serif')
f = plt.figure(figsize=(4,4))
ax = f.add_subplot(111)
ax.xaxis.set_minor_locator(MultipleLocator(1))
ax.xaxis.set_major_locator(MultipleLocator(10))
ax.yaxis.set_minor_locator(MultipleLocator(1))
ax.yaxis.set_major_locator(MultipleLocator(10))
majc ="#3182bd"
minc ="#deebf7"
ax.xaxis.grid(True,'minor',color=minc, ls='-', lw=0.2)
ax.yaxis.grid(True,'minor',color=minc, ls='-', lw=0.2)
ax.xaxis.grid(True,'major',color=majc, ls='-')
ax.yaxis.grid(True,'major',color=majc,ls ='-')
ax.set_axisbelow(True)
x = np.linspace(0, 30, 100)
ax.plot(x, x, 'r-', lw=0.7)
[line.set_zorder(3) for line in ax.lines]
plt.savefig('test.pdf')
Any suggestions? Thank you.
EDIT: close-up example
Upvotes: 4
Views: 2340
Reputation: 16249
Even more specifically, it looks like it draws vertical majors, vertical minors, horizontal majors, horizontal minors, and plotted lines, in that order. Probably pretty deep in the matplotlib basics.
For the colors you're using, you could work around by distinguishing major and minor by alpha, not RGB. Changing two lines of your example:
ax.xaxis.grid(True,'minor',color=majc, alpha=0.2, ls='-', lw=0.2)
ax.yaxis.grid(True,'minor',color=majc, alpha=0.2, ls='-', lw=0.2)
result:
Upvotes: 4