How to Set xlim and ylim in Matplotlib for Plot Limits
In Matplotlib, you set the x-axis limits using
plt.xlim(min, max) and the y-axis limits using plt.ylim(min, max). These functions control the visible range of data on each axis in your plot.Syntax
The basic syntax to set axis limits in Matplotlib is:
plt.xlim(left, right): Sets the limits of the x-axis fromlefttoright.plt.ylim(bottom, top): Sets the limits of the y-axis frombottomtotop.
You can also call these functions without arguments to get the current limits.
python
plt.xlim(left, right) plt.ylim(bottom, top)
Example
This example shows how to plot a simple line and then set the x-axis limits to 0 to 10 and y-axis limits to -1 to 1.
python
import matplotlib.pyplot as plt import numpy as np x = np.linspace(-5, 15, 100) y = np.sin(x) plt.plot(x, y) plt.xlim(0, 10) # Set x-axis limits from 0 to 10 plt.ylim(-1, 1) # Set y-axis limits from -1 to 1 plt.title('Plot with set xlim and ylim') plt.show()
Output
A line plot of sine wave visible only between x=0 and x=10 with y-axis from -1 to 1
Common Pitfalls
Common mistakes when setting axis limits include:
- Setting limits outside the data range, which can show empty plot areas.
- Confusing the order of arguments (e.g.,
plt.xlim(right, left)instead ofplt.xlim(left, right)). - Calling
plt.xlim()orplt.ylim()before plotting data, which may reset limits unexpectedly.
Always set limits after plotting your data.
python
import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 5, 50) y = x**2 plt.plot(x, y) # Wrong: limits reversed plt.xlim(10, 0) # This will invert the x-axis unintentionally plt.ylim(0, 30) plt.title('Incorrect xlim usage') plt.show() # Correct usage plt.plot(x, y) plt.xlim(0, 10) # Proper order plt.ylim(0, 30) plt.title('Correct xlim usage') plt.show()
Output
First plot shows inverted x-axis from 10 to 0; second plot shows normal x-axis from 0 to 10
Quick Reference
| Function | Purpose | Parameters |
|---|---|---|
| plt.xlim(left, right) | Set x-axis limits | left: float (min x), right: float (max x) |
| plt.ylim(bottom, top) | Set y-axis limits | bottom: float (min y), top: float (max y) |
| plt.xlim() | Get current x-axis limits | No parameters |
| plt.ylim() | Get current y-axis limits | No parameters |
Key Takeaways
Use plt.xlim(left, right) and plt.ylim(bottom, top) to set axis limits in Matplotlib.
Always set axis limits after plotting your data to avoid unexpected resets.
Ensure the order of limits is correct: left < right for xlim, bottom < top for ylim.
Setting limits outside your data range can cause empty plot areas.
You can call plt.xlim() or plt.ylim() without arguments to check current limits.