How to change the range of the X-axis and Y-axis in Matplotlib?

To change the range of X and Y axes in Matplotlib, we can use xlim() and ylim() methods. These methods allow you to set custom minimum and maximum values for both axes.

Using xlim() and ylim() Methods

The xlim() and ylim() methods accept two parameters: the minimum and maximum values for the respective axis ?

import numpy as np
import matplotlib.pyplot as plt

# Set the figure size and adjust the padding between and around the subplots
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

# Create x and y data points using numpy
x = np.linspace(-15, 15, 100)
y = np.sin(x)

# Plot x and y data points
plt.plot(x, y)

# Set the X and Y axes limit
plt.xlim(-10, 10)
plt.ylim(-1, 1)

# Display the figure
plt.show()

Alternative Method Using axis()

You can also use the axis() method to set both X and Y limits simultaneously ?

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(-15, 15, 100)
y = np.cos(x)

plt.plot(x, y, color='red', label='cosine')

# Set both X and Y limits using axis([xmin, xmax, ymin, ymax])
plt.axis([-8, 8, -1.2, 1.2])

plt.legend()
plt.title('Cosine Wave with Custom Axis Range')
plt.show()

Setting Individual Axis Limits

You can also set minimum and maximum values separately for more control ?

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 20, 100)
y = np.exp(-x/5) * np.cos(x)

plt.plot(x, y, 'b-', linewidth=2)

# Set limits separately
plt.xlim(left=2, right=15)  # Only set left and right bounds
plt.ylim(bottom=-0.5, top=1)  # Only set bottom and top bounds

plt.grid(True)
plt.title('Exponentially Decaying Cosine')
plt.show()

Comparison

Method Syntax Best For
xlim() / ylim() plt.xlim(min, max) Setting individual axis ranges
axis() plt.axis([xmin, xmax, ymin, ymax]) Setting both axes at once
Individual parameters plt.xlim(left=min, right=max) Setting only one bound

Conclusion

Use xlim() and ylim() for individual axis control, or axis() to set both ranges simultaneously. These methods help focus on specific data regions and improve plot readability.

Updated on: 2026-03-25T22:52:33+05:30

80K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements