Setting axis limits helps you focus on a specific part of your plot. It makes your graph clearer and easier to understand.
0
0
Axis limits (xlim, ylim) in Matplotlib
Introduction
You want to zoom in on a particular range of data points.
You want to compare two plots with the same axis scale.
You want to hide irrelevant data outside a certain range.
You want to set fixed axis limits for consistent visuals.
You want to improve the readability of crowded plots.
Syntax
Matplotlib
plt.xlim(min_value, max_value) plt.ylim(min_value, max_value)
Use plt.xlim() to set limits on the x-axis.
Use plt.ylim() to set limits on the y-axis.
Examples
Sets x-axis from 0 to 10 and y-axis from 0 to 5.
Matplotlib
plt.xlim(0, 10) plt.ylim(0, 5)
Sets the left limit of x-axis to 2 and top limit of y-axis to 8, keeping other limits unchanged.
Matplotlib
plt.xlim(left=2) plt.ylim(top=8)
Sets the right limit of x-axis to 15 and bottom limit of y-axis to 1.
Matplotlib
plt.xlim(right=15) plt.ylim(bottom=1)
Sample Program
This code plots prime numbers with x from 1 to 10 and y as prime values. The axis limits zoom in on x between 3 and 8, and y between 4 and 20, so you see a focused part of the data.
Matplotlib
import matplotlib.pyplot as plt x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] y = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] plt.plot(x, y, marker='o') plt.title('Prime Numbers Plot') plt.xlabel('X values') plt.ylabel('Y values') plt.xlim(3, 8) # Show x-axis from 3 to 8 plt.ylim(4, 20) # Show y-axis from 4 to 20 plt.grid(True) plt.show()
OutputSuccess
Important Notes
If you set limits outside your data range, the plot will show empty space.
You can also get current limits by calling plt.xlim() or plt.ylim() without arguments.
Setting limits after plotting is common to adjust the view.
Summary
Use plt.xlim() and plt.ylim() to control what part of the data you see.
Axis limits help focus on important data and improve plot clarity.
You can set limits fully or partially (left, right, top, bottom).