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

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


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


If you only want to put in a line or two you can use

ax.axhline(y, linestyle='--', color='k') # horizontal lines
ax.axvline(x, linestyle='--', color='k') # vertical lines

with line style and color (or all the rest of line/artist properties) set to what ever you want


To improve the answer of @tacaswell here's an example using the concept of axhline and tweaking it to look similar to a line grid. In this exapmle it's used a starting default grid only on the x-axis, but it's possible to add a grid also on the y-axis (or only on this axis) by simpy add ax.xaxis.grid(True) to the code.

First one simply start drawing a line at the desired position:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.xaxis.grid(True)
ynew = 0.3
ax.axhline(ynew)

plt.show()

obtaining the following result

grid1

that is not very similar to a line grid.
By changing color and line width like below:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.xaxis.grid(True)
ynew = 0.3
ax.axhline(ynew, color='gray', linewidth=0.5)

plt.show()

we obtain this, that now is in practice equal to a line grid.

grid2

If then we want also to add a tick and related label on the y-axis, in the position where the new line is:

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots()
ax.xaxis.grid(True)
ynew = 0.3
ax.axhline(ynew, color='gray', linewidth=0.5)

yt = ax.get_yticks()
yt=np.append(yt,ynew)

ax.set_yticks(yt)
ax.set_yticklabels(yt)

plt.show()

that leads to:

grid3

Oh no! Some approximation occurred and the label at 0.6 not represents exactly the number 0.6. Don't worry, we can fix that simply by rounding the label array like follow:

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots()
ax.xaxis.grid(True)
ynew = 0.3
ax.axhline(ynew, color='gray', linewidth=0.5)

yt = ax.get_yticks()
yt=np.append(yt,ynew)

ax.set_yticks(yt)
ax.set_yticklabels(np.round(yt,1))

plt.show()

and TA-DAAA :)

grid4