Setting Limits for Axis in Matplotlib

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.

  • But you can also set the limits explicitly.
  • There are two functions available by which you can easily set the limits explicitly:
    • set_xlim() for setting the limit of the x-axis
    • set_ylim() for setting the limit of the y-axis

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 axis value limit in matplotlib

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:

setting axis value limit in matplotlib
Follow Us On