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))
Additional Resources
The following tutorials explain how to perform other common tasks in Matplotlib:
How to Set Axis Ticks in Matplotlib
How to Increase Plot Size in Matplotlib
How to Add Text to Matplotlib Plots