How to Set the X and the Y Limit in Matplotlib with Python?
Last Updated :
03 Oct, 2022
In this article, we will learn how to set the X limit and Y limit in Matplotlib with Python.
- Matplotlib is a visualization library supported by Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. It was introduced by John Hunter in the year 2002.
- xlim() is a function in the Pyplot module of the Matplotlib library which is used to get or set the x-limits of the current axes.
- ylim() is a function in the Pyplot module of the Matplotlib library which is used to get or set the y-limits of the current axes.
Creating a Plot to Set the X and the Y Limit in Matplotlib
Python3
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace( - 10 , 10 , 1000 )
y = np.sin(x)
plt.plot(x, y)
|
Output:
Simple Plot
Example 1: Set X-Limit using xlim in Matplotlib
Python3
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace( - 10 , 10 , 1000 )
y = np.sin(x)
plt.plot(x, y)
plt.xlim( - 5 , 5 )
|
Output :
X limited Plot
Example 2: How to Set Y-Limit ylim in Matplotlib
Python3
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace( - 10 , 10 , 1000 )
y = np.cos(x)
plt.plot(x, y)
plt.ylim( 0 , 1 )
|
Output :
Y Limited Plot
Example 3: Set the X and the Y Limit in Matplotlib using xlim and ylim
Python3
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace( - 10 , 10 , 20 )
y = x
plt.plot(x, y)
plt.xlim( 0 )
plt.ylim( 0 )
|
Output :
X and Y Limited Plot
RECOMMENDED ARTICLES – Formatting Axes in Python-Matplotlib
Share your thoughts in the comments
Please Login to comment...