Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
88 changes: 88 additions & 0 deletions content/matplotlib/concepts/pyplot/terms/xlim/xlim.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
---
Title: '.xlim()'
Description: 'Used to get or set the x-axis limits of the current axes in Matplotlib plot'
Subjects:
- 'Data Science'
- 'Data Visualization'
Tags:
- 'Functions'
- 'Matplotlib'
- 'Subplots'
CatalogContent:
- 'learn-python-3'
- 'paths/data-science'
---

The **`.xlim()`** function is a convenient utility in [`matplotlib.pyplot`](https://www.codecademy.com/resources/docs/matplotlib/pyplot) that is used to get or set the x-axis limits of the current plot. It allows you to control the visible range of data on the x-axis, zoom in on specific sections, or ensure consistency 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

```pseudo
matplotlib.pyplot.xlim(left=None, right=None, emit=True, auto=False, *, xmin=None, xmax=None)
```

**Parameters:**

- `left` or `xmin`: Lower limit of the x-axis.
- `right` or `xmax`: Upper limit of the x-axis.
- `emit`: Whether observers are notified of the axis limit change (default: True).
- `auto`: If True, turns on automatic scaling.

**Return value:**

The `.xlim()` function returns a tuple containing (xmin, xmax) representing the current x-axis limits.

## Example 1: Basic X-Axis Limit Setting with `.xlim()`

This example shows how to set specific x-axis limits using `.xlim()`.

```py
import matplotlib.pyplot as plt
import numpy as np

x = 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 limits
plt.xlim(0, 10)

plt.grid(True)
plt.show()
```

The output generated by this code will be:

![Line plot showing sine wave with limited x-axis range](https://raw.githubusercontent.com/SrikartikMateti/docs/main/media/xlim-Plot-1.png)

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 only show data between x = 0 and x = 10. As a result, you see only the first half of the sine wave. The curve appears smooth and purple, with grid lines and labeled axes for clarity.

## Example 2: Get Current Axis Limits

You can call `.xlim()` with no arguments to retrieve the current axis limits

```py
import matplotlib.pyplot as plt

plt.plot([0, 1, 2, 3], [10, 20, 25, 30])
print(plt.xlim()) # Outputs current x-axis limits
```

The output generated by this code will be:

![Line plot of points (0,10), (1,20), (2,25), (3,30) with automatically determined x-axis limits.](https://raw.githubusercontent.com/SrikartikMateti/docs/main/media/xlim-Plot-2.png)

In this case, the output:
(np.float64(-0.15), np.float64(3.15))
indicates that Matplotlib automatically adds a small margin around the plotted points for better visualization.
You can also use `.xlim()` after plotting to dynamically adjust the x-axis limits, as shown in Example 1.