How to Set Axis Range in Matplotlib?

As a Python developer with over a decade of experience, I’ve worked extensively with data visualization libraries, and Matplotlib stands out as one of the most versatile tools for creating insightful charts.

One common challenge I’ve faced is controlling the axis ranges to make my plots clearer and more focused, especially when working with real-world data like US economic indicators or sales figures. In this article, I’ll share practical methods to set and customize axis ranges in Matplotlib.

Let’s get in!

Methods to Set Axis Ranges in Matplotlib

By default, Matplotlib automatically adjusts axis limits based on your data. While convenient, this can sometimes lead to misleading graphs or plots that don’t emphasize the important aspects of your data. For example, if you’re visualizing quarterly sales data for a US retail chain, you might want to zoom in on a specific revenue range to better illustrate growth trends.

Setting axis ranges gives you control over your plot’s appearance, improves readability, and helps your audience focus on the key insights.

Check out Python Matplotlib tick_params

1: Use set_xlim() and set_ylim() Functions

The simple way to set axis ranges is by using the set_xlim() and set_ylim() Python methods on your axes object. These functions let you specify the minimum and maximum limits for the x-axis and y-axis, respectively.

Here’s a quick example using US population growth data over the years:

import matplotlib.pyplot as plt

years = [2010, 2011, 2012, 2013, 2014, 2015]
population = [309, 311, 313, 316, 318, 320]  # in millions

fig, ax = plt.subplots()
ax.plot(years, population, marker='o')

# Set x-axis range from 2010 to 2016
ax.set_xlim(2010, 2016)

# Set y-axis range from 300 to 330 million
ax.set_ylim(300, 330)

ax.set_title('US Population Growth (2010-2015)')
ax.set_xlabel('Year')
ax.set_ylabel('Population (millions)')

plt.show()

You can refer to the screenshot below to see the output.

matplotlib set axis range

This method is intuitive and works well when you know the exact range you want to display.

Read Matplotlib tight_layout

2: Use plt.xlim() and plt.ylim() Functions

If you’re working with the pyplot interface and prefer a more functional style, plt.xlim() and plt.ylim() serve the same purpose.

import matplotlib.pyplot as plt

months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun']
sales = [25000, 27000, 30000, 28000, 35000, 40000]

plt.plot(months, sales, marker='s')

# Set x-axis range (indices for categorical data)
plt.xlim(-0.5, 5.5)

# Set y-axis range to focus on sales between 20000 and 45000
plt.ylim(20000, 45000)

plt.title('Monthly Sales for US Retail Chain')
plt.xlabel('Month')
plt.ylabel('Sales (USD)')

plt.show()

You can see the output in the screenshot below to see the output.

matplotlib axis range

Note: When working with categorical data like months, you might need to adjust axis limits based on index positions.

Check out Matplotlib set_yticklabels

3: Use axis() Function for Quick Range Setting

Python Matplotlib’s axis() function lets you set both x and y limits at once by passing a list of four values: [xmin, xmax, ymin, ymax].

import matplotlib.pyplot as plt
import numpy as np

days = np.arange(1, 8)
temperatures = [75, 77, 74, 79, 80, 78, 76]  # Fahrenheit

plt.plot(days, temperatures, marker='^')

# Set axis ranges: x from day 1 to 7, y from 70 to 85
plt.axis([1, 7, 70, 85])

plt.title('Daily Temperatures in New York City')
plt.xlabel('Day of Week')
plt.ylabel('Temperature (°F)')

plt.show()

You can refer to the screenshot below to see the output.

matplotlib axis limits

This method is handy for quick adjustments when you want to set both axes simultaneously.

Read Matplotlib fill_between

4: Adjust Axis Scale with set_xscale() and set_yscale()

Sometimes, it’s not just about the range but how the axis values are scaled. For data like US stock market indices or economic growth rates, a logarithmic scale can reveal trends hidden by linear scales.

import matplotlib.pyplot as plt
import numpy as np

years = np.arange(2000, 2010)
gdp = [10, 12, 15, 20, 28, 40, 55, 80, 120, 180]  # in trillion USD

plt.plot(years, gdp, marker='o')

plt.yscale('log')  # Set y-axis to logarithmic scale
plt.ylim(10, 200)

plt.title('US GDP Growth (2000-2009) - Log Scale')
plt.xlabel('Year')
plt.ylabel('GDP (Trillions USD)')

plt.show()

Using set_xscale() or set_yscale() with ‘log’ can make your visualizations more meaningful when dealing with exponential growth or wide-ranging data.

Check out Matplotlib set_xticklabels

5: Set Axis Limits Dynamically Based on Data

In some cases, you want to set axis limits dynamically, such as adding padding around your data points for better visualization.

import matplotlib.pyplot as plt
import numpy as np

years = np.array([2015, 2016, 2017, 2018, 2019])
unemployment_rate = np.array([5.3, 4.9, 4.4, 3.9, 3.7])  # in percent

plt.plot(years, unemployment_rate, marker='d')

# Calculate padding
x_padding = 0.5
y_padding = 0.5

plt.xlim(years.min() - x_padding, years.max() + x_padding)
plt.ylim(unemployment_rate.min() - y_padding, unemployment_rate.max() + y_padding)

plt.title('US Unemployment Rate (2015-2019)')
plt.xlabel('Year')
plt.ylabel('Unemployment Rate (%)')

plt.show()

This approach ensures your plot isn’t too cramped and provides a clean margin around your data.

Read Matplotlib set_xticks

Tips for Effective Axis Range Setting

  • Always consider the story your data tells. Setting axis ranges too narrowly or too broadly can mislead the viewer.
  • For time series or categorical data, ensure axis limits align correctly with your data points.
  • Use logarithmic scales thoughtfully and explain them in your chart titles or legends.
  • When sharing plots with others, maintain consistent axis ranges across similar charts for easy comparison.

I hope these methods make it easier for you to customize your Matplotlib plots. Setting axis ranges is a simple yet powerful way to improve the clarity and impact of your visualizations. If you have any questions or want to share your tips, feel free to leave a comment below!

You may also read Matplotlib-related tutorials:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.