grid() (Matplotlib)

ax.grid() draws reference grid lines across a plot at the tick positions, making it easier to read values off the chart. You can toggle it on or off and style the lines.

Matplotlib

A call to ax.grid(True) overlays light lines aligned with the axis ticks so the eye can trace a data point back to its x and y values. This is especially helpful on line and scatter plots where precise reading matters.

You can restrict the grid to one direction with axis='x' or axis='y', and style the lines with the usual keywords — color, linestyle, linewidth, alpha — to keep them subtle. The which argument chooses whether lines appear at the major ticks, the minor ticks, or both.

Grids are a readability aid, not data, so keep them faint; heavy grid lines compete with the data they are meant to support. Many style sheets, like 'ggplot' and 'seaborn', enable a tasteful grid by default.

Syntax

ax.grid(visible=True, which='major', axis='both')

Examples

Python — Grid lines are now enabled on the Axes.

import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.grid(True)
print(ax.xaxis._major_tick_kw.get("gridOn", True))

Output:

True

Learn it in a lesson

See also

Back to the Dictionary