How to Set Axis Limits in Matplotlib: Simple Guide
To set axis limits in Matplotlib, use
plt.xlim(min, max) for the x-axis and plt.ylim(min, max) for the y-axis. These functions control the visible range of data on each axis in your plot.Syntax
Use plt.xlim() and plt.ylim() to set the limits of the x-axis and y-axis respectively.
plt.xlim(min, max): Sets the lower and upper limits of the x-axis.plt.ylim(min, max): Sets the lower and upper limits of the y-axis.- Both functions accept two numbers: the minimum and maximum values to display.
python
import matplotlib.pyplot as plt plt.xlim(0, 10) # Set x-axis limits from 0 to 10 plt.ylim(-5, 5) # Set y-axis limits from -5 to 5
Example
This example shows how to plot a simple line and set custom axis limits to zoom in on a specific part of the data.
python
import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 20, 100) y = np.sin(x) plt.plot(x, y) plt.xlim(5, 15) # Show x-axis from 5 to 15 plt.ylim(-1, 1) # Show y-axis from -1 to 1 plt.title('Sine Wave with Custom Axis Limits') plt.xlabel('X axis') plt.ylabel('Y axis') plt.show()
Output
A plot window showing a sine wave curve with the x-axis limited from 5 to 15 and 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.
- Using
plt.axis()incorrectly by passing a tuple with wrong order or values. - Forgetting to call
plt.show()to display the plot after setting limits.
python
import matplotlib.pyplot as plt x = [1, 2, 3, 4, 5] y = [10, 20, 25, 30, 40] plt.plot(x, y) # Correct: limits within data range plt.xlim(1, 5) plt.ylim(10, 40) plt.show()
Output
A plot showing the data with axis limits matching the data range, avoiding empty space.
Quick Reference
| Function | Purpose | Example Usage |
|---|---|---|
| plt.xlim(min, max) | Set x-axis limits | plt.xlim(0, 10) |
| plt.ylim(min, max) | Set y-axis limits | plt.ylim(-5, 5) |
| plt.axis([xmin, xmax, ymin, ymax]) | Set all axis limits at once | plt.axis([0, 10, -1, 1]) |
Key Takeaways
Use plt.xlim(min, max) and plt.ylim(min, max) to set axis limits in Matplotlib.
Set axis limits within the data range to avoid empty plot areas.
Call plt.show() after setting limits to display the plot.
plt.axis([xmin, xmax, ymin, ymax]) can set all limits at once.
Axis limits help zoom in or focus on specific parts of your plot.