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 packages import matplotlib.pyplot as plt import numpy as np # create data x = np.linspace( - 10 , 10 , 1000 ) y = np.sin(x) # plot the graph plt.plot(x, y) |
Output:
Example 1: Set X-Limit using xlim in Matplotlib
Python3
# import packages import matplotlib.pyplot as plt import numpy as np # create data x = np.linspace( - 10 , 10 , 1000 ) y = np.sin(x) # plot the graph plt.plot(x, y) # limit x by -5 to 5 plt.xlim( - 5 , 5 ) |
Output :
Example 2: How to Set Y-Limit ylim in Matplotlib
Python3
# import packages import matplotlib.pyplot as plt import numpy as np # create data x = np.linspace( - 10 , 10 , 1000 ) y = np.cos(x) # plot the graph plt.plot(x, y) # limit y by 0 to 1 plt.ylim( 0 , 1 ) |
Output :
Example 3: Set the X and the Y Limit in Matplotlib using xlim and ylim
Python3
# import packages import matplotlib.pyplot as plt import numpy as np # create data x = np.linspace( - 10 , 10 , 20 ) y = x # plot the graph plt.plot(x, y) # limited to show positive axes plt.xlim( 0 ) plt.ylim( 0 ) |
Output :
RECOMMENDED ARTICLES – Formatting Axes in Python-Matplotlib