A Matplotlib plot can contain more data than the reader needs to see at once. Setting axis limits keeps the underlying data unchanged while focusing the visible x-axis or y-axis range on the interval that matters for comparison, review, or exported figures.
Axes.set_xlim() and Axes.set_ylim() set the view limits on one Axes object. The limit values use the same data coordinates as the plotted data, so -1.5 on the x-axis means the plotted x coordinate, not a screen position.
Call the limit setters after adding the plotted data, then save or show the figure. A printed get_xlim() or get_ylim() check confirms the active view limits, and the saved image shows the selected range.
import numpy as np import matplotlib.pyplot as plt x = np.linspace(-3, 3, 121) y = np.sinc(x) fig, ax = plt.subplots(layout="constrained") ax.plot(x, y, marker="o", markersize=3) ax.set_xlim(-1.5, 1.5) ax.set_ylim(-0.25, 1.05) ax.set_xlabel("Sample position") ax.set_ylabel("Response") ax.set_title("Axis limits focus the visible data range") fig.savefig("axis-limits-focused-plot.png", dpi=160) left, right = ax.get_xlim() bottom, top = ax.get_ylim() print(f"xlim=({left:.1f}, {right:.1f})") print(f"ylim=({bottom:.2f}, {top:.2f})") print("saved=axis-limits-focused-plot.png")
NumPy only generates repeatable data here; replace x and y with project arrays. set_xlim(left, right) controls the x-axis view range, and set_ylim(bottom, top) controls the y-axis view range.
$ python axis-limits.py xlim=(-1.5, 1.5) ylim=(-0.25, 1.05) saved=axis-limits-focused-plot.png
Passing None for one side leaves the existing limit unchanged, such as ax.set_xlim(right=2). Passing the values in reverse order inverts that axis instead of sorting the numbers.