How to Save a Matplotlib Axis as PNG in Python

While working on a data visualization project in Python, I needed to save only one specific chart (axis) from a Matplotlib figure as a PNG file.

At first, I thought it would be simple, just use plt.savefig(), right? But I realized that saving a single axis instead of the entire figure needed a bit more control.

In this guide, I’ll show you how to save a specific Matplotlib axis as a PNG image using different methods. Each method is beginner-friendly and explained step-by-step, so you can easily choose the one that fits your workflow.

Method 1 – Save the Entire Figure as PNG Using savefig()

Before we get into saving a specific axis, let’s start with the basics. The most common way to save a Matplotlib figure in Python is by using the savefig() function.

This method saves the entire figure (including all axes) as a PNG image.

Here’s a simple example:

import matplotlib.pyplot as plt

# Create a figure with two subplots
fig, axes = plt.subplots(1, 2, figsize=(10, 4))

# Plot data on each axis
axes[0].plot([1, 2, 3, 4], [10, 20, 25, 30], color='blue', label='Sales')
axes[0].set_title('Sales Growth')

axes[1].bar(['Q1', 'Q2', 'Q3', 'Q4'], [15, 25, 35, 45], color='green', label='Revenue')
axes[1].set_title('Quarterly Revenue')

# Save the entire figure as a PNG file
plt.savefig('full_figure.png', dpi=300, bbox_inches='tight')

# Show the figure
plt.show()

You can see the output in the screenshot below.

How to Save Matplotlib Axis as PNG Python

In this example, the savefig() function saves the entire figure (both subplots) as a single PNG file named full_figure.png.

The dpi=300 ensures that the image is high-resolution, suitable for printing or professional reports. The bbox_inches=’tight’ ensures that labels and titles are not cut off.

Method 2 – Save a Specific Axis as PNG Using bbox_inches

Now, let’s move to the main goal, saving only one axis from a Matplotlib figure as a PNG image. This is useful when you have multiple subplots but only want to export one of them, such as a revenue chart for a presentation.

Here’s how you can do it:

import matplotlib.pyplot as plt

# Create a figure with two subplots
fig, axes = plt.subplots(1, 2, figsize=(10, 4))

# Plot on each axis
axes[0].plot([1, 2, 3, 4], [100, 200, 250, 300], color='red', label='Profit')
axes[0].set_title('Profit Over Time')

axes[1].bar(['Jan', 'Feb', 'Mar', 'Apr'], [50, 70, 90, 120], color='orange', label='Expenses')
axes[1].set_title('Monthly Expenses')

# Save only the second axis as PNG
extent = axes[1].get_window_extent().transformed(fig.dpi_scale_trans.inverted())
fig.savefig('expenses_axis.png', bbox_inches=extent, dpi=300)

plt.show()

You can see the output in the screenshot below.

Save a Matplotlib Axis as PNG in Python

In this code, we use the get_window_extent() method to get the bounding box of the axis we want to save.

Then, we pass that bounding box to the bbox_inches parameter of savefig(). This ensures only the selected axis (in this case, the “Monthly Expenses” chart) is saved as a PNG image.

Method 3 – Save a Matplotlib Axis Using Figure.savefig() and Axes.figure

Another method I often use is calling the savefig() function directly from the axis’s figure object. This gives you more flexibility, especially when working with dynamic figures in large Python projects.

Here’s a practical example:

import matplotlib.pyplot as plt

# Create figure and axis
fig, ax = plt.subplots(figsize=(6, 4))

# Plot sample data
x = [1, 2, 3, 4, 5]
y = [10, 15, 25, 30, 45]
ax.plot(x, y, color='purple', marker='o', label='Growth Rate')

ax.set_title('Company Growth Rate')
ax.set_xlabel('Year')
ax.set_ylabel('Percentage')

# Save the axis using its figure reference
ax.figure.savefig('growth_rate_axis.png', dpi=300, bbox_inches='tight')

plt.show()

You can see the output in the screenshot below.

How to Save Matplotlib Axis as PNG

In this example, I called ax.figure.savefig() instead of plt.savefig(). This approach is especially helpful when you’re working with multiple figures in the same Python script and want to save specific plots without confusion.

Method 4 – Save Multiple Axes Individually in a Loop

In some cases, you may want to save multiple axes separately, for example, when you’re generating multiple charts for a report or dashboard.

You can easily automate this process using Python for loop.

Here’s how I usually do it:

import matplotlib.pyplot as plt
import numpy as np

# Create multiple subplots
fig, axes = plt.subplots(2, 2, figsize=(10, 8))

# Generate sample data
x = np.linspace(0, 10, 100)

# Plot different functions
functions = [np.sin, np.cos, np.tan, np.exp]
titles = ['Sine Wave', 'Cosine Wave', 'Tangent', 'Exponential']

# Loop through each axis and save individually
for i, ax in enumerate(axes.flat):
    y = functions[i](x)
    ax.plot(x, y, label=titles[i])
    ax.set_title(titles[i])
    ax.legend()

    # Define file name based on title
    filename = f"{titles[i].lower().replace(' ', '_')}.png"

    # Save each axis
    extent = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
    fig.savefig(filename, bbox_inches=extent, dpi=300)

plt.show()

You can see the output in the screenshot below.

Save Python Matplotlib Axis as PNG

In this Python example, each subplot is automatically saved as a separate PNG file with a descriptive filename.

This method is extremely useful when you’re generating multiple visualizations programmatically, for example, saving daily charts for a U.S.-based sales dashboard.

Method 5 – Save Matplotlib Axis as PNG Using BytesIO (Without Saving to Disk)

Sometimes, you may want to save your Matplotlib axis as a PNG without writing it to disk, for example, when integrating with a web application or sending the image via email.

You can use Python’s built-in io.BytesIO module for this purpose.

Here’s a complete example:

import matplotlib.pyplot as plt
import io

# Create a sample plot
fig, ax = plt.subplots(figsize=(6, 4))
ax.plot([1, 2, 3, 4], [5, 7, 9, 12], color='teal', marker='s', label='Data')
ax.set_title('Online Data Visualization')
ax.legend()

# Save axis to a BytesIO object
buf = io.BytesIO()
extent = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
fig.savefig(buf, format='png', bbox_inches=extent, dpi=300)
buf.seek(0)

# You can now use 'buf' as an image stream (for web apps or APIs)
print("Axis saved to memory as PNG stream!")

In this Python example, the axis is saved as a PNG image in memory. You can then use this image stream directly in Flask, Django, or FastAPI applications, perfect for real-time chart rendering in dashboards.

Additional Tips for Saving Matplotlib Axes as PNG

Here are some quick professional tips from my experience:

  • Always use dpi=300 for print-quality images.
  • Use bbox_inches=’tight’ to ensure labels aren’t cut off.
  • To save transparent backgrounds, add transparent=True to savefig().
  • For consistent output, call plt.tight_layout() before saving.
  • When saving multiple axes, ensure each has a unique filename to avoid overwriting.

These small tweaks can make a big difference in the final quality of your exported charts.

Saving a specific Matplotlib axis as a PNG in Python might seem tricky at first, but once you understand how bbox_inches and get_window_extent() work, it becomes second nature.

Whether you’re preparing a presentation, automating report generation, or building a web dashboard, the methods I shared above will help you export your plots cleanly and efficiently.

I personally use the bbox_inches approach most often because it gives me precise control over what part of the figure gets saved.

You may also like to read:

Leave a Comment

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.