W3docs

How to set the y-axis limit

In matplotlib, you can set the limit of the y-axis of a plot by using the set_ylim() method of the Axes class.

In matplotlib, you can set the limit of the y-axis of a plot by using the set_ylim() method of the Axes class. The method takes a tuple of two values, the lower and upper limit of the y-axis.

For example, to set the y-axis limit of a plot to the range (-1, 1):

Set the y-axis limit of a plot to the range (-1, 1) in Python using matplotlib

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)
y = np.sin(x)

fig, ax = plt.subplots()
ax.plot(x, y)
ax.set_ylim(-1, 1)
plt.show()

In case you want to set the limit of the x-axis, you can use the set_xlim() method.

Setting the x-axis limit using set_xlim() in matplotlib

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)
y = np.sin(x)

fig, ax = plt.subplots()
ax.plot(x, y)
ax.set_xlim(0, 5)
plt.show()