Matplotlib’s add_axes

While working on a project, I’ve found that mastering data visualization is crucial for effectively communicating insights. Matplotlib remains one of the most powerful and flexible libraries for creating plots. If you’ve ever struggled with subplot layouts or wanted to position a plot exactly where you want it, add_axes is the best choice.

In this article, I’ll share my firsthand experience with add_axes and show you how to use it effectively, especially when working with real-world datasets like US economic or demographic data.

Let’s get in!

What is add_axes in Matplotlib?

In simple terms, add_axes allows you to add a new axes (plotting area) to a figure at an exact location and size you specify. Unlike plt.subplot() or plt.subplots(), which arrange plots in a grid, add_axes lets you place your plot anywhere by defining the axes’ position and size in the figure coordinate system.

This is particularly useful when you want to create custom layouts, inset plots, or overlays without being constrained by grid layouts.

Read Matplotlib Update Plot in Loop

How Does add_axes Work?

The method takes a list of four numbers as an argument: [left, bottom, width, height]. These numbers represent the position and size of the axes, measured as fractions of the figure’s width and height.

  • left: Distance from the left edge of the figure to the left edge of the axes (0 to 1)
  • bottom: Distance from the bottom edge of the figure to the bottom edge of the axes (0 to 1)
  • width: Width of the axes (fraction of figure width)
  • height: Height of the axes (fraction of figure height)

For example, [0.1, 0.1, 0.8, 0.8] creates an axes that starts 10% from the left and bottom and spans 80% of the figure’s width and height.

Check out Make a Multiline Plot from CSV File in Matplotlib

Method 1: Basic Usage of add_axes

Here’s how I typically use add_axes when I want a plot in a custom position.

import matplotlib.pyplot as plt

fig = plt.figure()

# Add axes at [left, bottom, width, height]
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])

# Example: Plotting US unemployment rate over time
years = [2018, 2019, 2020, 2021, 2022]
unemployment_rate = [3.9, 3.7, 8.1, 5.4, 3.6]

ax.plot(years, unemployment_rate, marker='o')
ax.set_title('US Unemployment Rate (2018-2022)')
ax.set_xlabel('Year')
ax.set_ylabel('Unemployment Rate (%)')

plt.show()

I executed the above example code and added the screenshot below.

fig.add_axes

In this example, I created an axes occupying most of the figure but positioned with a margin. This approach is straightforward and perfect for single plots or when you want total control over axes size and location.

Read Module ‘matplotlib’ has no attribute ‘plot’

Method 2: Create Inset Plots with add_axes

One of the powerful uses of add_axes is to create inset plots, smaller plots inside a bigger one. This is handy when you want to zoom in or highlight a specific region of your data.

Here’s an example where I plot US GDP growth and add an inset focusing on 2020-2022.

fig = plt.figure()
main_ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])

years = [2018, 2019, 2020, 2021, 2022]
gdp_growth = [2.9, 2.3, -3.4, 5.7, 2.1]

main_ax.plot(years, gdp_growth, marker='o')
main_ax.set_title('US GDP Growth Rate (2018-2022)')
main_ax.set_xlabel('Year')
main_ax.set_ylabel('GDP Growth (%)')

# Add inset axes [left, bottom, width, height]
inset_ax = fig.add_axes([0.6, 0.5, 0.25, 0.3])
inset_ax.plot(years[2:], gdp_growth[2:], color='red', marker='o')
inset_ax.set_title('Zoom: 2020-2022')
inset_ax.set_xticks(years[2:])
inset_ax.grid(True)

plt.show()

I executed the above example code and added the screenshot below.

add_axes

By specifying the inset axes position manually, I can control exactly where the zoomed plot appears, making my visualization clearer and more informative.

Check out Matplotlib Set y Axis Range

Method 3: Combine add_axes with Other Plot Types

add_axes is flexible enough to mix different plot types or add multiple axes in the same figure without the constraints of subplot grids.

For example, I often overlay a bar chart with a line chart using separate axes:

fig = plt.figure()

# Bar chart axes
bar_ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
states = ['California', 'Texas', 'Florida', 'New York']
population = [39.1, 29.0, 21.5, 19.8]  # in millions

bar_ax.bar(states, population, color='skyblue')
bar_ax.set_ylabel('Population (millions)')
bar_ax.set_title('Population by State')

# Line chart axes overlay
line_ax = fig.add_axes([0.1, 0.1, 0.8, 0.8], frameon=False)
line_ax.plot(states, [3.2, 2.8, 2.5, 3.0], color='red', marker='o')
line_ax.set_ylabel('Unemployment Rate (%)', color='red')
line_ax.tick_params(axis='y', colors='red')
line_ax.yaxis.set_label_position("right")
line_ax.yaxis.tick_right()

plt.show()

I executed the above example code and added the screenshot below.

fig add_axes

Here, I created two axes in the same position. The second axis has no frame, so it overlays the first one perfectly, allowing me to compare two related datasets visually.

Read Module ‘matplotlib’ has no attribute ‘artist’

Tips from My Experience with add_axes

  • Always remember the coordinates are fractions of the figure size, so [0,0,1,1] covers the entire figure.
  • Use fig.add_axes() instead of plt.axes() when you want to add axes to a specific figure, especially when handling multiple figures.
  • When working with complex layouts, sketch your desired axes positions on paper to visualize the fractions before coding.
  • Combine add_axes with figure size adjustments (figsize) to fine-tune your plots’ appearance.
  • For interactive or dynamic plots, consider using add_axes with event handling to create responsive visualizations.

I hope this guide helps you harness the full power of Matplotlib’s add_axes. Whether you’re visualizing US economic trends, demographic data, or any other dataset, add_axes gives you the precision and flexibility to create compelling, professional charts.

If you want to dive deeper, explore Matplotlib’s other layout tools like GridSpec or subplot2grid can complement your knowledge of add_axes.

You may also like to read:

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.