How do I get the axis limits in Matplotlib (With an Example)

In Matplotlib, the axis limits can be set using the set_xlim and set_ylim functions. For example, if you wanted to set the x-axis limits to be from 0 to 10 and the y-axis limits to be from 0 to 20, you would use the following code: ax.set_xlim(0,10) and ax.set_ylim(0,20). The resulting plot would show the data points within the specified limits.


You can use the following syntax to get the axis limits for both the x-axis and y-axis of a plot in Matplotlib:

import matplotlib.pyplot as plt

#get x-axis and y-axis limits
xmin, xmax, ymin, ymax = plt.axis()

#print axis limits
print(xmin, xmax, ymin, ymax)

The following example shows how to use this syntax in practice.

Example: How to Get Axis Limits in Matplotlib

Suppose we create the following scatterplot in Matplotlib:

import matplotlib.pyplot as plt

#define x and y
x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
y = [1, 5, 9, 15, 24, 39, 35, 35, 40, 41]

#create scatter plot of x vs. y
plt.scatter(x, y)

We can use the following syntax to get the axis limits for both the x-axis and y-axis of the scatterplot:

import matplotlib.pyplot as plt

#define x and y
x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
y = [1, 5, 9, 15, 24, 39, 35, 35, 40, 41]

#create scatter plot of x vs. y
plt.scatter(x, y)

#get x-axis and y-axis limits
xmin, xmax, ymin, ymax = plt.axis()

#print axis limits
print(xmin, xmax, ymin, ymax)

0.55 10.45 -1.0 43.0

From the output we can see:

  • x-axis minimum: 0.55
  • x-axis maximum: 10.45
  • y-axis minimum: -1.0
  • y-axis maximum: 43.0

These values match the axis limits that can be seen in the scatterplot above.

We can also use the annotate() function to add these axis limits as text values to the plot if we’d like:

import matplotlib.pyplot as plt

#define x and y
x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
y = [1, 5, 9, 15, 24, 39, 35, 35, 40, 41]

#create scatter plot of x vs. y
plt.scatter(x, y)

#get x-axis and y-axis limits
xmin, xmax, ymin, ymax = plt.axis()

#print axis limits
lims = 'xmin: ' + str(round(xmin, 2)) + 'n' + 
       'xmax: ' + str(round(xmax, 2)) + 'n' + 
       'ymin: ' + str(round(ymin, 2)) + 'n' + 
       'ymax: ' + str(round(ymax, 2))

#add axis limits to plot at (x,y) coordinate (1,35)
plt.annotate(lims, (1, 35))

Matplotlib get axis limits

The following tutorials explain how to perform other common tasks in Matplotlib:

x