Grid lines make a Matplotlib chart easier to read when values need to be compared against tick marks rather than only against the plotted line. Keeping them light and behind the data gives line charts, bar charts, and scatter plots visible reference points without changing the plotted values.
Axes.grid() changes the grid on the specific Axes object, so the object-oriented interface keeps the setting attached to the chart being exported. Use axis=“y” when horizontal reference lines are enough, axis=“both” when both directions help, and which to choose major ticks, minor ticks, or both.
Minor grid lines need minor tick positions before they can appear. Set a minor locator such as AutoMinorLocator(), keep the grid below the plotted data with set_axisbelow(True), and use a light color or alpha so the grid supports the data instead of competing with it.
Related: How to set axis labels in Matplotlib
Related: How to set axis limits in Matplotlib
Related: How to save a Matplotlib figure
from pathlib import Path import matplotlib.pyplot as plt from matplotlib.ticker import AutoMinorLocator, MultipleLocator output = Path("grid-enable.png") weeks = ["W1", "W2", "W3", "W4", "W5", "W6"] incidents = [48, 43, 39, 41, 35, 31] fig, ax = plt.subplots(figsize=(6.2, 3.6), layout="constrained") ax.plot(weeks, incidents, marker="o", linewidth=2.2, color="tab:blue") ax.set_title("Open incidents by week") ax.set_xlabel("Week") ax.set_ylabel("Open incidents") ax.set_ylim(25, 55) ax.yaxis.set_major_locator(MultipleLocator(10)) ax.yaxis.set_minor_locator(AutoMinorLocator(2)) ax.set_axisbelow(True) ax.grid(True, axis="y", which="major", color="0.78", linewidth=0.9) ax.grid(True, axis="y", which="minor", color="0.90", linestyle=":", linewidth=0.6) fig.canvas.draw() major_y_grid = [line for line in ax.get_ygridlines() if line.get_visible()] minor_y_grid = [ tick.gridline for tick in ax.yaxis.get_minor_ticks() if tick.gridline.get_visible() ] fig.savefig(output, dpi=160) plt.close(fig) print(f"major y grid lines: {len(major_y_grid)}") print(f"minor y grid lines: {len(minor_y_grid)}") print(f"axis below data: {ax.get_axisbelow()}") print(f"saved: {output}") print(f"bytes: {output.stat().st_size}")
axis=“y” draws horizontal grid lines only. Use axis=“both” when vertical grid lines make the x positions easier to compare.
$ python grid_enable.py major y grid lines: 5 minor y grid lines: 4 axis below data: True saved: grid-enable.png bytes: 36261
The byte count can change with Matplotlib, font, backend, or DPI differences. A nonzero byte count confirms that the PNG was written.
The plot should show solid horizontal major grid lines at the labeled y ticks and lighter dotted minor grid lines between them.
ax.grid(True, axis="both", which="major", color="0.82", linewidth=0.8)
Passing style keyword arguments such as color, linestyle, linewidth, or alpha also turns the grid on.
ax.yaxis.set_minor_locator(AutoMinorLocator(2)) ax.grid(True, axis="y", which="minor", color="0.90", linestyle=":", linewidth=0.6)
Minor ticks are off by default in many plots. Without minor tick locations, which=“minor” has no minor positions to draw.
ax.set_axisbelow(True)
Use set_axisbelow(“line”) when grid lines should sit above filled patches but below line and marker artists.
$ rm grid_enable.py grid-enable.png