Home » How to Set Axis Ranges in Matplotlib

How to Set Axis Ranges in Matplotlib

by Erma Khan

You can use the following syntax to set the axis ranges for a plot in Matplotlib:

#specify x-axis range 
plt.xlim(1, 15)

#specify y-axis range
plt.ylim(1, 30)

The following examples show how to use this syntax in practice.

Example 1: Specify Both Axes Ranges

The following code shows how to specify the range for both axes:

import matplotlib.pyplot as plt

#define x and y
x = [1, 4, 10]
y = [5, 11, 27]

#create plot of x and y
plt.plot(x, y)

#specify x-axis and y-axis range
plt.xlim(1, 15)
plt.ylim(1, 30)

Example 2: Specify Range for X-Axis Only

The following code shows how to specify the range for the x-axis only:

import matplotlib.pyplot as plt

#define x and y
x = [1, 4, 10]
y = [5, 11, 27]

#create plot of x and y
plt.plot(x, y)

#specify x-axis range
plt.xlim(1, 15)

Example 3: Specify Range for Y-Axis Only

The following code shows how to specify the range for the y-axis only:

import matplotlib.pyplot as plt

#define x and y
x = [1, 4, 10]
y = [5, 11, 27]

#create plot of x and y
plt.plot(x, y)

#specify y-axis range
plt.ylim(1, 30)

Additional Resources

How to Set Tick Labels Font Size in Matplotlib
How to Increase Plot Size in Matplotlib
How to Add Text to Matplotlib Plots

Related Posts