Matplotlib Grid
Grid lines give a Matplotlib chart visual reference points, making values easier to read at a glance.
Turning on the grid
Calling plt.grid() adds light reference lines across the plot at each tick mark on both axes, which makes it much easier to read off approximate values without hovering over the actual data points.
Example
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [3, 7, 4, 9, 6]
plt.plot(x, y)
plt.grid()
plt.show()Showing grid lines on one axis
The axis argument limits the grid to just the x-axis or just the y-axis instead of both, which is useful when only one dimension of the chart needs reference lines, for example when only horizontal comparison matters.
Example
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [10, 14, 12, 18, 15]
plt.plot(x, y)
plt.grid(axis="y")
plt.show()Styling the grid lines
plt.grid() accepts the same styling keywords used elsewhere in Matplotlib: color to set the line color, linestyle to change the dash pattern, linewidth to set thickness, and alpha to control transparency so the grid stays subtle behind your data.
Example
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [5, 9, 6, 11, 8]
plt.plot(x, y, marker="o")
plt.grid(color="gray", linestyle="--", linewidth=0.5, alpha=0.7)
plt.show()Used sparingly, a grid makes a chart easier to read; used heavily, it can compete with the data for attention, so keep grid lines subtle with muted colors and partial transparency.