Save Matplotlib Graph as PNG in Python

Recently, while working on a data visualization project for a client in New York, I needed to save several charts created using Matplotlib as high-quality PNG files.

At first, I assumed it would be as simple as clicking a “Save” button. But when I looked closer, I realized that saving Matplotlib graphs as PNG images required a few extra steps to get the best results.

In this tutorial, I’ll walk you through how to save Matplotlib graph as PNG file in Python, step by step. I’ll share not only the basic method but also some advanced options I’ve learned from over a decade of working with Python and data visualization.

What is Matplotlib in Python?

Matplotlib is one of the most popular Python libraries for data visualization. It allows you to create a wide range of plots, from simple line charts to detailed heatmaps, all with just a few lines of Python code.

When you’re done creating your chart, you often need to export it as an image file, such as PNG, JPG, or PDF, for reports, presentations, or websites.

Among all formats, PNG is one of the most preferred because it provides lossless quality and transparent backgrounds, making it ideal for professional use.

Save Matplotlib Graphs as PNG Files

Before jumping into the code, let’s quickly understand why PNG is a great choice:

  • High Quality: PNG supports high-resolution images without compression artifacts.
  • Transparency Support: You can save plots with transparent backgrounds.
  • Scalability: Works well for both web and print.
  • Cross-Platform: PNG files can be easily shared and viewed anywhere.

Now that we know why PNG is great, let’s see how to save a Matplotlib graph as a PNG in Python.

Method 1 – Save Matplotlib Graph as PNG Using savefig()

The easiest and most common method to save a Matplotlib graph as a PNG file is by using the savefig() function.

Here’s a simple example that demonstrates how to do it in Python.

Example: Basic Save as PNG

import matplotlib.pyplot as plt

# Create sample data
x = [1, 2, 3, 4, 5]
y = [10, 15, 13, 17, 20]

# Create a line plot
plt.plot(x, y, color='blue', linewidth=2, marker='o')
plt.title("Sales Growth Over 5 Years (USA)")
plt.xlabel("Year")
plt.ylabel("Sales (in millions)")

# Save the plot as a PNG file
plt.savefig("sales_growth.png")

# Show the plot
plt.show()

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

Save Matplotlib Graph as PNG in Python

In this example, I created a simple line chart showing sales growth over five years. The line plt.savefig(“sales_growth.png”) saves the graph as a PNG file in your current working directory.

Once you run this Python script, you’ll find a sales_growth.png file created in the same folder.

Add Full File Path

If you want to save the file in a specific directory, you can provide the full path.

plt.savefig("C:/Users/John/Desktop/sales_growth.png")

This ensures your PNG file is stored exactly where you want it.

Method 2 – Save Matplotlib Graph as High-Resolution PNG

When creating visualizations for reports or publications, you often need high-resolution images. You can easily control the output quality by using the dpi (dots per inch) parameter in the savefig() function.

Example: Save High-Resolution PNG File

import matplotlib.pyplot as plt

# Sample data
months = ["Jan", "Feb", "Mar", "Apr", "May"]
revenue = [12000, 15000, 18000, 22000, 26000]

# Create a bar chart
plt.bar(months, revenue, color='green')
plt.title("Monthly Revenue - 2025 (USA)")
plt.xlabel("Month")
plt.ylabel("Revenue ($)")
plt.grid(True, linestyle='--', alpha=0.6)

# Save high-resolution PNG
plt.savefig("monthly_revenue_highres.png", dpi=300)

plt.show()

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

Save Python Matplotlib Graph as PNG

Here, I’ve set dpi=300, which produces a crisp, publication-quality PNG image. The higher the DPI, the better the image quality, but also the larger the file size.

Method 3 – Save Matplotlib PNG Without White Borders

Sometimes, when saving a Matplotlib figure, you’ll notice unwanted white borders around your graph.

To remove these borders, use the bbox_inches=’tight’ parameter in savefig().

Example: Save PNG Without Borders

import matplotlib.pyplot as plt

# Data
cities = ["New York", "Los Angeles", "Chicago", "Houston", "Phoenix"]
population = [8.4, 4.0, 2.7, 2.3, 1.7]

# Create bar chart
plt.bar(cities, population, color='skyblue')
plt.title("Population of Major U.S. Cities (in millions)")
plt.xlabel("City")
plt.ylabel("Population")

# Save without extra white space
plt.savefig("us_cities_population.png", bbox_inches='tight', dpi=300)

plt.show()

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

Save Graph as PNG in Python Matplotlib

The bbox_inches=’tight’ argument ensures the saved PNG image tightly fits around the plot area, removing unnecessary margins.

Method 4 – Save Matplotlib Graph with Transparent Background

If you’re adding the PNG file to a presentation or website with a colored background, transparency can make your plots look more professional.

You can achieve this by setting the parameter transparent=True in the savefig() function.

Example: Save PNG with Transparent Background

import matplotlib.pyplot as plt

# Data
x = [1, 2, 3, 4, 5]
y = [5, 9, 7, 11, 14]

# Create plot
plt.plot(x, y, color='red', linewidth=3, marker='o')
plt.title("Growth Trend (Transparent Background)")
plt.xlabel("Quarter")
plt.ylabel("Growth Rate (%)")

# Save transparent PNG
plt.savefig("growth_trend_transparent.png", transparent=True, dpi=300)

plt.show()

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

Save Graph as PNG in Matplotlib Python

Now, your PNG will have a transparent background, making it blend seamlessly into any design or slide.

Method 5 – Save Multiple Matplotlib Graphs as PNG in a Loop

In real-world Python projects, you might need to generate and save multiple plots automatically.

Here’s how you can do that efficiently using a simple loop.

Example: Save Multiple PNG Files in a Loop

import matplotlib.pyplot as plt
import numpy as np

# Sample datasets
datasets = {
    "Q1": np.random.randint(50, 100, 5),
    "Q2": np.random.randint(60, 110, 5),
    "Q3": np.random.randint(70, 120, 5),
    "Q4": np.random.randint(80, 130, 5)
}

months = ["Jan", "Feb", "Mar", "Apr", "May"]

# Loop through each dataset and save PNG
for quarter, data in datasets.items():
    plt.figure()
    plt.plot(months, data, marker='o', linewidth=2)
    plt.title(f"Quarterly Sales - {quarter} (USA)")
    plt.xlabel("Month")
    plt.ylabel("Sales ($ in thousands)")
    plt.grid(True, linestyle='--', alpha=0.5)
    plt.savefig(f"{quarter}_sales_chart.png", dpi=300, bbox_inches='tight')
    plt.close()

This Python script automatically creates and saves four separate PNG charts, one for each quarter. Using plt.close() ensures each figure is closed after saving, preventing memory issues.

Method 6 – Save Matplotlib Graph as PNG Using Object-Oriented Approach

Many experienced Python developers prefer the object-oriented (OO) interface of Matplotlib for better control.

Here’s how you can use it to save a graph as PNG.

Example: Use Figure and Axes Objects

import matplotlib.pyplot as plt

# Create figure and axes
fig, ax = plt.subplots()

# Data
years = [2020, 2021, 2022, 2023, 2024]
profits = [200, 250, 300, 400, 500]

# Plot data
ax.plot(years, profits, color='purple', marker='s', linewidth=2)
ax.set_title("Company Profit Growth (USA)")
ax.set_xlabel("Year")
ax.set_ylabel("Profit ($ in thousands)")

# Save figure as PNG
fig.savefig("company_profit_growth.png", dpi=300, bbox_inches='tight')

plt.show()

The OO approach is cleaner and more scalable when you’re building complex dashboards or multi-plot figures in Python.

Common Mistakes When Saving PNG Files in Matplotlib

Here are a few common issues I’ve seen developers face:

  • Blank PNG files: Usually caused by calling plt.savefig() after plt.show(). Always save before showing the plot.
  • Low-quality images: Set dpi=300 or higher for professional output.
  • Wrong file path: Use absolute paths or verify the working directory with os.getcwd().

Bonus Tip – Save PNG and Display Plot Simultaneously

If you want to save the PNG and also display it interactively, just call plt.savefig() before plt.show().

plt.savefig("chart.png", dpi=300)
plt.show()

This ensures the image is saved correctly and still appears in the output window.

So, that’s how you can save your Matplotlib graph as a PNG file in Python, quickly and efficiently. We covered multiple methods, from simple savefig() usage to advanced options like transparency, high resolution, and automated saving in loops.

I’ve personally used these techniques across dozens of Python projects, from financial dashboards to analytics reports, and they’ve never failed me.

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.