How to Set Axis Ranges in Matplotlib?
Last Updated :
30 Sep, 2022
Matplotlib sets the default range of the axis by finding extreme values (i.e. minimum and maximum) on that axis. However, to get a better view of data sometimes the Pyplot module is used to set axis ranges of the graphs according to the requirements in Matplotlib. Following is the method used to set the axis range in Matplotlib.
Setting Axis Range in Matplotlib
Set X-Limit (xlim) in Matplotlib
Syntax: matplotlib.pyplot.xlim(limit_range)
Set Y-Limit (xlim) in Matplotlib
Syntax: matplotlib.pyplot.ylim(limit_range)
How to Set Axis Ranges in Matplotlib
Creating a Plot
Let us plot the sine wave function without setting the axis range:
Python
import matplotlib.pyplot as plt
import numpy as np
x = np.arange( 0 , 10 , 0.1 )
y = np.sin(x)
plt.plot(y, color = 'blue' )
plt.show()
|
Output:
Set X-Limit (xlim) in Matplotlib
Now, we will set the x-axis range of the plot as [0, 60]. Following is the code for restricting the range of the x-axis.
Python
import matplotlib.pyplot as plt
import numpy as np
x = np.arange( 0 , 10 , 0.1 )
y = np.sin(x)
plt.plot(y, color = 'blue' )
plt.xlim( 0 , 60 )
plt.show()
|
Output:
Set Y-Limit (ylim) in Matplotlib
Now, we will set the y-axis range of the plot as [0, 1]. Following is the code for restricting the range of the y-axis.
Python
import matplotlib.pyplot as plt
import numpy as np
x = np.arange( 0 , 10 , 0.1 )
y = np.sin(x)
plt.plot(y, color = 'blue' )
plt.ylim( 0 , 1 )
plt.show()
|
Output:
Set X-Limit (xlim) and Y-Limit (ylim) in Matplotlib
We can also set the range for both axes of the plot at the same time. Now, we will set the x-axis range as [0, 32] and y axis range as [0, 1]. Following is the code for restricting the range of the x-axis and y-axis.
Python
import matplotlib.pyplot as plt
import numpy as np
x = np.arange( 0 , 10 , 0.1 )
y = np.sin(x)
plt.plot(y, color = 'blue' )
plt.xlim( 0 , 32 )
plt.ylim( 0 , 1 )
plt.show()
|
Output:
Share your thoughts in the comments
Please Login to comment...