Open In App

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

In this article, we will learn how to set the X limit and Y limit in Matplotlib with Python.

Creating a Plot to Set the X and the Y Limit in Matplotlib




# 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:



Simple Plot

Example 1: Set X-Limit using xlim in Matplotlib




# 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 :

X limited Plot

Example 2: How to Set Y-Limit ylim in Matplotlib




# 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 :



Y Limited Plot

Example 3: Set the X and the Y Limit in Matplotlib using xlim and ylim




# 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 :

X and Y Limited Plot

RECOMMENDED ARTICLES – Formatting Axes in Python-Matplotlib


Article Tags :