How to set axis limits in Matplotlib

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.

Steps to set Matplotlib axis limits:

  1. Create a plot script that sets the x-axis and y-axis limits on the same Axes object.
    axis-limits.py
    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.

  2. Run the script to save the figure and print the active limits.
    $ python axis-limits.py
    xlim=(-1.5, 1.5)
    ylim=(-0.25, 1.05)
    saved=axis-limits-focused-plot.png
  3. Check the saved figure for the focused x and y ranges.

    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.