How to Set Axis Ranges in Matplotlib
Creating a Plot
Let us plot the sine wave function without setting the axis range:
Python
# import packages import matplotlib.pyplot as plt import numpy as np # return values between 0 and 10 with # even space of 0.1 x = np.arange( 0 , 10 , 0.1 ) # generate value of sine function for # given x values y = np.sin(x) # plot graph of sine function plt.plot(y, color = 'blue' ) # display plot 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 packages import matplotlib.pyplot as plt import numpy as np # return values between 0 and 10 with # even space of 0.1 x = np.arange( 0 , 10 , 0.1 ) # generate value of sine function for # given x values y = np.sin(x) # plot graph of sine function plt.plot(y, color = 'blue' ) # Set the range of x-axis plt.xlim( 0 , 60 ) # display plot 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 packages import matplotlib.pyplot as plt import numpy as np # return values between 0 and 10 with # even space of 0.1 x = np.arange( 0 , 10 , 0.1 ) # generate value of sine function for # given x values y = np.sin(x) # plot graph of sine function plt.plot(y, color = 'blue' ) # Set the range of y-axis plt.ylim( 0 , 1 ) # display plot 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 packages import matplotlib.pyplot as plt import numpy as np # return values between 0 and 10 with # even space of 0.1 x = np.arange( 0 , 10 , 0.1 ) # generate value of sine function for # given x values y = np.sin(x) # plot graph of sine function plt.plot(y, color = 'blue' ) # Set the range of x-axis plt.xlim( 0 , 32 ) # Set the range of y-axis plt.ylim( 0 , 1 ) # display plot plt.show() |
Output:
How to Set Axis Ranges in Matplotlib?
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.