How to Set Axis Range in Matplotlib (Python)


Let’s see how we can set the axis range in Matplotlib in Python using the xlim() and ylim() functions.

Suppose we’re trying to plot the datapoints below.

import matplotlib.pyplot as plt
plt.plot([1, 2, 3, 4])
# TODO: set axis range
plt.show()

1. Setting the X-Axis Range

To set the x-axis range, we can use the xlim() function. This function takes in two arguments, the first being the lower bound of the range and the second being the upper bound of the range.

plt.xlim(0, 5)

2. Setting the Y-Axis Range

To set the y-axis range, we can use the ylim() function. This function also takes in two arguments, the first being the lower bound of the range and the second being the upper bound of the range.

plt.ylim(0, 5)

3. Setting Both X and Y Axis Ranges at Once

To set both x and y axis ranges at once, we can use the axis() function. This function takes in four arguments: the first two are the x-axis range and the second two are the y-axis range.

plt.axis([0, 5, 0, 5])