How to change axes limits in Seaborn (and Matplotlib)

In this quick recipe we’ll learn how to define axis limits for our Seaborn and Matplotlib plots in Python.

For convenience, I’ll use Seaborn in this example, but the methods we’ll use in order to resize the axis limits are first and foremost part of Matplotlib and can be used on every pyplot chart.

Set axis limits in Seaborn and Matplotlib with Axes.set_xlim and set_ylim

Consider the following code that deliver the scatter plot we see below.

fig, scatter = plt.subplots(figsize = (10,6), dpi = 100)
scatter = sns.scatterplot(x = 'mass', y ='distance', data=data);

Seems that except a few outliers, so probably we can focus our data analysis on the bottom left part of our sns.scatter plot chart.

Let us fo ahead and redefine new limits for both axes in our plot using the following script.

# with xlim/ylim
fig, scatter = plt.subplots(figsize = (10,6), dpi = 100)
scatter = sns.scatterplot(x = 'mass', y ='distance', data=data)
scatter.set_xlim(left=0, right=6)
scatter.set_ylim(bottom=0, top=200);

Here’s our chart, note the new ranges for both the X and y axes. Note that for better clarity you might want to resize your Seaborn plot as needed.

Although we used an sns.scatterplot as an example, all the above works on the other Seaborn charts: boxplot, barplot, catplot, lineplot etc’

Follow up questions? Happy to answer your comments.

Leave a Comment