0
0
MatplotlibHow-ToBeginner ยท 3 min read

How to Set xlim and ylim in Matplotlib for Plot Limits

In Matplotlib, you set the x-axis limits using plt.xlim(min, max) and the y-axis limits using plt.ylim(min, max). These functions control the visible range of data on each axis in your plot.
๐Ÿ“

Syntax

The basic syntax to set axis limits in Matplotlib is:

  • plt.xlim(left, right): Sets the limits of the x-axis from left to right.
  • plt.ylim(bottom, top): Sets the limits of the y-axis from bottom to top.

You can also call these functions without arguments to get the current limits.

python
plt.xlim(left, right)
plt.ylim(bottom, top)
๐Ÿ’ป

Example

This example shows how to plot a simple line and then set the x-axis limits to 0 to 10 and y-axis limits to -1 to 1.

python
import matplotlib.pyplot as plt
import numpy as np

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

plt.plot(x, y)
plt.xlim(0, 10)  # Set x-axis limits from 0 to 10
plt.ylim(-1, 1)  # Set y-axis limits from -1 to 1
plt.title('Plot with set xlim and ylim')
plt.show()
Output
A line plot of sine wave visible only between x=0 and x=10 with y-axis from -1 to 1
โš ๏ธ

Common Pitfalls

Common mistakes when setting axis limits include:

  • Setting limits outside the data range, which can show empty plot areas.
  • Confusing the order of arguments (e.g., plt.xlim(right, left) instead of plt.xlim(left, right)).
  • Calling plt.xlim() or plt.ylim() before plotting data, which may reset limits unexpectedly.

Always set limits after plotting your data.

python
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 5, 50)
y = x**2

plt.plot(x, y)
# Wrong: limits reversed
plt.xlim(10, 0)  # This will invert the x-axis unintentionally
plt.ylim(0, 30)
plt.title('Incorrect xlim usage')
plt.show()

# Correct usage
plt.plot(x, y)
plt.xlim(0, 10)  # Proper order
plt.ylim(0, 30)
plt.title('Correct xlim usage')
plt.show()
Output
First plot shows inverted x-axis from 10 to 0; second plot shows normal x-axis from 0 to 10
๐Ÿ“Š

Quick Reference

FunctionPurposeParameters
plt.xlim(left, right)Set x-axis limitsleft: float (min x), right: float (max x)
plt.ylim(bottom, top)Set y-axis limitsbottom: float (min y), top: float (max y)
plt.xlim()Get current x-axis limitsNo parameters
plt.ylim()Get current y-axis limitsNo parameters
โœ…

Key Takeaways

Use plt.xlim(left, right) and plt.ylim(bottom, top) to set axis limits in Matplotlib.
Always set axis limits after plotting your data to avoid unexpected resets.
Ensure the order of limits is correct: left < right for xlim, bottom < top for ylim.
Setting limits outside your data range can cause empty plot areas.
You can call plt.xlim() or plt.ylim() without arguments to check current limits.