Cannot get minor grid lines to appear in matplotlib figure

Solution 1:

Unfortunately, ax.grid is a bit confusing in this regard. (This is a design bug / common gotcha.) It turns the minor grid on, but the minor ticks are still turned off.

What you need to do is call plt.minorticks_on or ax.minorticks_on in addition to calling ax.grid(True, which='both').

Solution 2:

You should use plt.minorticks_on().

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure(1)
ax = fig.add_subplot(111)

x = np.linspace(0,10,41)
y = np.sin(x)

plt.plot(x,y)
plt.grid(b=True, which='major', color='k', linestyle='-')
plt.grid(b=True, which='minor', color='r', linestyle='-', alpha=0.2)
plt.minorticks_on()
plt.show()