Peter Saxton Peter Saxton - 6 months ago 165
Python Question

How to create Major and Minor gridlines with different Linestyles in Python

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 properies
which=both/major/mine and then color and linestyle are defined simply by linestyle, is there any 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='-')

Answer

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

Comments