Python:Matplotlib .xlim()
The .xlim() function in matplotlib.pyplot is used to get or set the x-axis limits of the current plot. It helps control the visible range of data on the x-axis, zoom in on specific sections, or maintain consistent axis ranges across multiple plots.
The primary use cases for .xlim() include:
- Focusing on a particular range of x-values.
- Maintaining consistent axis scaling between multiple plots.
- Preventing automatic resizing that hides important data.
Syntax
matplotlib.pyplot.xlim(*args, **kwargs)
Parameters:
The function accepts the following keyword arguments:
leftorxmin(float, optional): Lower limit of the x-axis.rightorxmax(float, optional): Upper limit of the x-axis.emit(bool, default: True): Whether observers are notified of the axis limit change (default: True).auto(bool, default: True): IfTrue, turns on automatic scaling.
Return value:
The .xlim() function returns a tuple (xmin, xmax) representing the current x-axis limits.
Example 1: Setting Custom X-Axis Limits
This example shows how to set specific x-axis limits using .xlim():
import matplotlib.pyplot as pltimport numpy as npx = np.linspace(0, 20, 100)y = np.sin(x)plt.plot(x, y, color='purple', linewidth=2)plt.title('Sine Wave with Custom X Limits')plt.xlabel('X')plt.ylabel('sin(x)')# Set x-axis limitsplt.xlim(0, 10)plt.grid(True)plt.show()
The output generated by this code will be:

This code plots a sine wave from 0 to 20 on the x-axis, but the plt.xlim(0, 10) command restricts the visible range to data between x = 0 and x = 10. As a result, only the first half of the sine wave is displayed. The curve appears smooth and purple, with grid lines and labeled axes for clarity.
Example 2: Getting Current X-Axis Limits
Calling .xlim() without arguments retrieves the current x-axis limits:
import matplotlib.pyplot as pltplt.plot([0, 1, 2, 3], [10, 20, 25, 30])print(plt.xlim()) # Outputs current x-axis limitsplt.show()
The output generated by this code will be:

In this case, the output is:
(np.float64(-0.15), np.float64(3.15))
This indicates that Matplotlib automatically adds a small margin around the plotted points for better visualization. The .xlim() function can also be applied after plotting to dynamically adjust the x-axis limits, as demonstrated in Example 1.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python:Matplotlib on Codecademy
- Machine Learning Data Scientists solve problems at scale, make predictions, find patterns, and more! They use Python, SQL, and algorithms.
- Includes 27 Courses
- With Professional Certification
- Beginner Friendly.95 hours
- Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
- With Certificate
- Beginner Friendly.24 hours