153

I am currently using matplotlib.pyplot to create graphs and would like to have the major gridlines solid and black and the minor ones either greyed or dashed.

In the grid properties, which=both/major/mine, and then color and linestyle are defined simply by linestyle. Is there a way to specify minor linestyle only?

The appropriate code I have so far is

plt.plot(current, counts, 'rd', markersize=8)
plt.yscale('log')
plt.grid(b=True, which='both', color='0.65', linestyle='-')
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Peter Saxton
  • 4,466
  • 5
  • 33
  • 51

2 Answers2

223

Actually, it is as simple as setting major and minor separately:

In [9]: plot([23, 456, 676, 89, 906, 34, 2345])
Out[9]: [<matplotlib.lines.Line2D at 0x6112f90>]

In [10]: yscale('log')

In [11]: grid(b=True, which='major', color='b', linestyle='-')

In [12]: grid(b=True, which='minor', color='r', linestyle='--')

The gotcha with minor grids is that you have to have minor tick marks turned on too. In the above code this is done by yscale('log'), but it can also be done with plt.minorticks_on().

enter image description here

joaquin
  • 82,968
  • 29
  • 138
  • 152
  • 52
    Sometimes you also need to call `plt.minorticks_on()` for the minor grid to actually appear. See http://stackoverflow.com/a/19940830/209246 – eqzx Feb 06 '17 at 22:34
  • 3
    From the [docs](https://matplotlib.org/devdocs/api/_as_gen/matplotlib.pyplot.grid.html): "If kwargs are supplied, it is assumed that you want a grid and b is thus set to True." - so you might omit `b=True`. – miku Oct 30 '17 at 20:11
  • I have tried doing the same with double log plot. Unfortunately the x-axis shows only the major thicks. Is it possible to switch on also the minor thicks. – Alexander Cska Apr 08 '18 at 17:56
  • 1
    @Alexander you need to add `axis="both"` parameter to the `plt.grid()` function. – Kanmani Feb 22 '19 at 05:26
  • 2
    Is there a rcParam property to make this as the default style ? – Kanmani Mar 28 '19 at 01:54
  • 1
    To whom who may use this answer with Matplotlib 3.5+: the 'b' parameter of grid() has been renamed 'visible' – codkelden Sep 11 '22 at 11:21
24

A simple DIY way would be to make the grid yourself:

import matplotlib.pyplot as plt

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

ax.plot([1,2,3], [2,3,4], 'ro')

for xmaj in ax.xaxis.get_majorticklocs():
  ax.axvline(x=xmaj, ls='-')
for xmin in ax.xaxis.get_minorticklocs():
  ax.axvline(x=xmin, ls='--')

for ymaj in ax.yaxis.get_majorticklocs():
  ax.axhline(y=ymaj, ls='-')
for ymin in ax.yaxis.get_minorticklocs():
  ax.axhline(y=ymin, ls='--')
plt.show()
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
ev-br
  • 24,968
  • 9
  • 65
  • 78