Skip to content
Related Articles

Related Articles

How to Set the X and the Y Limit in Matplotlib with Python?

View Discussion
Improve Article
Save Article
  • Last Updated : 03 Oct, 2022
View Discussion
Improve Article
Save Article

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:

Set the X and the Y Limit in Matplotlib

Simple Plot

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 :

Set the X and the Y Limit in Matplotlib

X limited Plot

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 :

Set the X and the Y Limit in Matplotlib

Y Limited Plot

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 :

Set the X and the Y Limit in Matplotlib

X and Y Limited Plot

RECOMMENDED ARTICLES – Formatting Axes in Python-Matplotlib


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!