LAST UPDATED: OCTOBER 20, 2020
Setting Limits for Axis in Matplotlib
In this tutorial, we will cover how to set up the limits in the matplotlib for the X axis and Y axis values.
The Matplotlib Library automatically sets the minimum and maximum values of variables to be displayed along x, y (and z-axis in case of the 3D plot) axis of a plot.
Now we will cover two examples, in the first one, the limits are automatically set up by the matplotlib library while in our second example we will set up the limits explicitly.
Matplotlib Default Limits:
In the example given below the limits are set automatically by the matplotlib library.
import matplotlib.pyplot as plt
fig = plt.figure()
a1 = fig.add_axes([0,0,1,1])
import numpy as np
x = np.arange(1,10)
a1.plot(x, np.log(x))
a1.set_title('Logarithm')
plt.show()
Here is the output:
Setting Custom Limits in Matplotlib
Now in this example, we will set the limits explicitly using the functions discussed above. Let us take a look at the code:
import matplotlib.pyplot as plt
fig = plt.figure()
a1 = fig.add_axes([1,1,1,1])
import numpy as np
x = np.arange(1, 100)
a1.plot(x, np.exp(x),'c')
a1.set_title('Exponent')
# to set the y axis limits
a1.set_ylim(0, 10000)
# to set the x axis limits
a1.set_xlim(0, 10)
plt.show()
Here is the output:
Summary:
In this tutorial, we learned how to set the limits for the x axis and y axis to show the data properly. By default matplotlib also manages this well, but if you wish to explicilty mention these limts, you can use the set_xlim()
and set_ylim()
functions.