TExcelTAD
Home › Matplotlib › Matplotlib Grid

Matplotlib Grid

Grid lines help the eye travel from a data point to the axis to read its value. Matplotlib hides them by default; plt.grid() turns them on.

Adding grid lines

python · try it yourself
import matplotlib.pyplot as plt

minutes = [0, 5, 10, 15, 20, 25, 30]
heart_rate = [72, 95, 128, 141, 150, 138, 110]

plt.plot(minutes, heart_rate, marker="o")
plt.title("Heart rate during a run")
plt.xlabel("Minutes")
plt.ylabel("Beats per minute")
plt.grid()
plt.show()

ax = plt.gca()
print("Grid visible:", ax.xaxis.get_gridlines()[0].get_visible())
print("Vertical lines at x =", [int(t) for t in ax.get_xticks() if 0 <= t <= 30])
Grid visible: True
Vertical lines at x = [0, 5, 10, 15, 20, 25, 30]

Grid lines are drawn at the tick positions. If you change the ticks (see Ticks & Axis Scales), the grid follows.

Only one direction

axis="x" or axis="y" limits the grid to vertical or horizontal lines. Horizontal lines alone are a popular choice for bar and line charts, since you usually read values off the y axis:

python · try it yourself
import matplotlib.pyplot as plt

year = [2019, 2020, 2021, 2022, 2023]
members = [310, 280, 355, 420, 470]

plt.plot(year, members, marker="o")
plt.xticks(year)
plt.grid(axis="y")
plt.title("Club members")
plt.show()

ax = plt.gca()
print("x grid on:", ax.xaxis.get_gridlines()[0].get_visible())
print("y grid on:", ax.yaxis.get_gridlines()[0].get_visible())
x grid on: False
y grid on: True

Styling the grid

grid() accepts the same line properties as plot(): color, linestyle, linewidth and alpha (transparency from 0 to 1). A light, thin grid supports the data without competing with it:

python · try it yourself
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(-3, 3, 200)

plt.plot(x, x ** 3 - 3 * x, color="C3", lw=2)
plt.grid(color="gray", linestyle="--", linewidth=0.5, alpha=0.6)
plt.axhline(0, color="black", lw=0.8)    # emphasise y = 0
plt.axvline(0, color="black", lw=0.8)    # emphasise x = 0
plt.title(r"$f(x) = x^3 - 3x
quot;) plt.show() line = plt.gca().get_ygridlines()[0] print("grid style:", line.get_linestyle(), line.get_linewidth(), line.get_alpha())
grid style: -- 0.5 0.6

plt.axhline(y) and plt.axvline(x) draw lines across the whole Axes. They are perfect for marking zero, a target value or a threshold.

Major and minor grids

Ticks come in two kinds: major ticks (with labels) and minor ticks (small, unlabelled, between the major ones). Minor ticks are off by default. Turn them on with plt.minorticks_on() and give the minor grid a fainter style through which="minor":

python · try it yourself
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 10, 100)

plt.plot(x, np.sqrt(x))
plt.minorticks_on()
plt.grid(which="major", color="0.6", linewidth=0.8)
plt.grid(which="minor", color="0.85", linewidth=0.5, linestyle=":")
plt.title("Major and minor grid")
plt.show()

ax = plt.gca()
lo, hi = ax.get_xlim()
major = [float(t) for t in ax.get_xticks() if lo <= t <= hi]
minor = [t for t in ax.xaxis.get_minorticklocs() if lo <= t <= hi]
print("visible major x ticks:", major)
print("visible minor x ticks:", len(minor))
visible major x ticks: [0.0, 2.0, 4.0, 6.0, 8.0, 10.0]
visible minor x ticks: 17
Call Effect
plt.grid() Turn the major grid on
plt.grid(False) Turn it off
plt.grid(axis="y") Horizontal lines only
plt.grid(which="minor") Grid at minor ticks (needs minorticks_on())
plt.grid(which="both") Major and minor

Tip: To draw grid lines behind bars and other filled shapes, call plt.gca().set_axisbelow(True) (already the default for lines in most styles).

Test yourself

How do you show only horizontal grid lines?

  1. plt.grid(axis="x")
  2. plt.grid(axis="y")
  3. plt.hgrid()
  4. plt.grid(horizontal=True)

Where are grid lines drawn?

  1. Every 1 unit
  2. At the tick positions
  3. At each data point
  4. At random positions

Which function draws one horizontal line across the whole Axes at y = 0?

  1. plt.hline(0)
  2. plt.axhline(0)
  3. plt.grid(0)
  4. plt.plot(0)