Select Page

Solutions covered in this post are given below.

1. Set X axis and Y axis range
2. Set X axis LEFT limit only
3. Set X axis RIGHT limit only
4. Set Y axis BOTTOM limit only
5. Set Y axis TOP limit only

## Default plot without explicitly setting any axis range

```# Default plot without setting any limits
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [8, 4, 6, 3, 2]
plt.plot(x, y)
plt.xlabel("X values")
plt.ylabel("Y values")
plt.title("BEFORE setting axis range")
plt.show()```

## 1) Set X axis and Y axis range

matplotlib.pyplot.xlim(left, right)

matplotlib.pyplot.ylim(bottom, top)

Make sure to add this after the line where you actually plot “plt.plot(x, y)” for it to work properly.

```# Set  X axis and Y axis range
import matplotlib.pyplot as plt
plt.plot(x, y)
plt.xlim(0, 10)  # Set x-axis limits
plt.ylim(0, 10)  # Set y-axis limits
plt.xlabel("X values")
plt.ylabel("Y values")
plt.title("Change X axis and Y axis range")
plt.show()```

## 2) Set X axis LEFT limit only

matplotlib.pyplot.xlim(left=num)

Make sure to add this after the line where you actually plot “plt.plot(x, y)” for it to work properly.

```# Set X axis LEFT limit only
import matplotlib.pyplot as plt
plt.plot(x, y)
plt.xlim(left=0)
plt.xlabel("X values")
plt.ylabel("Y values")
plt.title("Change X axis LEFT limit only")
plt.show()```

## 3) Set X axis RIGHT limit only

matplotlib.pyplot.xlim(right=num)

Make sure to add this after the line where you actually plot “plt.plot(x, y)” for it to work properly.

```# Set X axis RIGHT limit only
import matplotlib.pyplot as plt
plt.plot(x, y)
plt.xlim(right=8)
plt.xlabel("X values")
plt.ylabel("Y values")
plt.title("Change X axis RIGHT limit only")
plt.show()```

## 4) Set Y axis BOTTOM limit only

matplotlib.pyplot.ylim(bottom=num)

Make sure to add this after the line where you actually plot “plt.plot(x, y)” for it to work properly.

```# Set Y axis BOTTOM limit only
import matplotlib.pyplot as plt
plt.plot(x, y)
plt.ylim(bottom=-2)
plt.xlabel("X values")
plt.ylabel("Y values")
plt.title("Change Y axis BOTTOM limit only")
plt.show()```

## 5) Set Y axis TOP limit only

matplotlib.pyplot.ylim(top=num)

Make sure to add this after the line where you actually plot “plt.plot(x, y)” for it to work properly.

```# Set Y axis TOP limit only
import matplotlib.pyplot as plt
plt.plot(x, y)
plt.ylim(top=10)
plt.xlabel("X values")
plt.ylabel("Y values")
plt.title("Change Y axis TOP limit only")
plt.show()```

A copy of the code used here is available in my GitHub.