xlim and ylim (Matplotlib)

set_xlim() and set_ylim() set the visible range of a plot's x and y axes, controlling how far each axis extends. They let you zoom in on a region or fix consistent scales across charts.

Matplotlib

By default Matplotlib auto-scales the axes to fit your data with a little padding. ax.set_xlim(0, 100) overrides that to show exactly the range you choose, which is how you zoom into a section or crop out distracting extremes. The pyplot forms are plt.xlim() and plt.ylim().

Passing the limits reversed — set_ylim(top, bottom) with the larger value first — flips the axis direction, a common trick for putting the origin at the top (as in image coordinates) or for descending rankings.

Calling the getter form, ax.get_xlim(), returns the current limits as a tuple, useful when you want to extend or compare ranges. To make several subplots share the same scale automatically, use sharex/sharey in subplots() instead of setting limits by hand.

Syntax

ax.set_xlim(left, right)  |  ax.set_ylim(bottom, top)

Examples

Python

import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.set_xlim(0, 10)
print(ax.get_xlim())

Output:

(0.0, 10.0)

Learn it in a lesson

See also

Back to the Dictionary