How to add a grid line at a specific location in matplotlib plot?

UNagaswamy picture UNagaswamy · Jan 30, 2013 · Viewed 40.6k times · Source

How do I add grid at a specific location on the y axis in a matplotlib plot?

Answer

Paul H picture Paul H · Jan 30, 2013

Yes. It's very simple. Use the set_[x|y]ticks methods of axes object and toggle the grid as normal:

import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.set_yticks([0.2, 0.6, 0.8], minor=False)
ax.set_yticks([0.3, 0.55, 0.7], minor=True)
ax.yaxis.grid(True, which='major')
ax.yaxis.grid(True, which='minor')
plt.show()

Custom tick locations