Open In App

How to change axes limits in matplotlib?

Last Updated : 16 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Sometimes, when you create a plot default axes X and Y may not show the full picture you want. Changing the axes limits helps you focus on specific data ranges or improve how your plot looks. There are two methods available in Axes module tochange the limits:

  1. matplotlib.axes.Axes.set_xlim(): It is used to set the x-axis view limits. We can specify the lower and upper bounds for the x-axis. This helps zoom in or zoom out graph along the x-axis to highlight specific portions of data.
  2. matplotlib.axes.Axes.set_ylim(): It is used to set the y-axis view limits. We can define the range for the y-axis to control which portion of the data is visible along y-axis.

Syntax:

Axes.set_xlim(self, left=None, right=None, emit=True, auto=False, *, xmin=None, xmax=None)
Axes.set_ylim(self, bottom=None, top=None, emit=True, auto=False, *, ymin=None, ymax=None)

Parameters:

  • bottom/top: Defines the lower/upper limit of the x or y axis in data coordinates.
  • emit: Notifies observers when the limit changes.
  • auto: Enables auto scaling for the axis.
  • xmin/xmax/ymin/ymax: Alternate methods for bottom and top. It will generate error if wepass both xmin/ymin and bottom or xmax/ymax and top.

Example 1:

Here ax.set_xlim(1, 70): This sets the limits for the x-axis(1- lower bound and 70 -upper bound )

Python
import seaborn as sns

data = [3, 7, 9, 11, 12, 14, 
        15, 16, 18, 19, 20, 
        23, 25, 28]

fig, ax = plt.subplots()
sns.distplot(data, ax=ax)
ax.set_xlim(1, 70)
plt.show()

Output:

Example 2:

Now lets see the implementation for matplotlib.axes.Axes.set_ylim().

Here we will load the “tips” dataset which is a built-in dataset in Seaborn. It contains information about restaurant bills and tips. Here gfg.set_ylim(0, 80) sets the y-axis limits and will range from 0 to 80 regardless of the data’s actual range.

Python
import seaborn as sns
import matplotlib.pyplot as plt
sns.set_style("whitegrid")

tips = sns.load_dataset("tips")

day_colors = {
    "Thur": "blue",   
    "Fri": "orange",  
    "Sat": "green",  
    "Sun": "red"    
}

gfg = sns.boxplot(x="day", y="total_bill", data=tips,
                  palette=day_colors)

gfg.set_ylim(0, 80)
plt.show()

Output:

Changing axes limits in Seaborn is a simple yet essential technique for customizing your visualizations. By adjusting the X and Y axis ranges, you can focus on specific areas of interest in your data, highlight important trends and improve overall clarity of your plots.

You can also read realted articles:



Next Article
Article Tags :
Practice Tags :

Similar Reads