Save Matplotlib Plots as PNG Images in Python

When I was working with data visualization tools. Matplotlib is one of my go-to libraries when it comes to creating insightful charts and graphs. A common task I often encounter is saving these visualizations as images, especially in PNG format, which is widely used for reports, presentations, and web applications.

If you’ve ever wondered how to save your Matplotlib plots as PNG files efficiently, you’re in the right place. In this article, I’ll share practical methods to save your plots as PNGs, along with tips to customize the output quality and size.

Let’s get in!

Methods to Save Matplotlib Plots as PNG?

PNG (Portable Network Graphics) is a popular image format thanks to its lossless compression and wide compatibility. When sharing data visualizations, PNG files maintain the quality of your charts without bloating the file size. This makes them ideal for embedding in documents, websites, or sharing with colleagues.

In my experience, saving plots as PNGs is often the final step after crafting your visualization in Matplotlib. The ability to control resolution and transparency can make a significant difference in how your charts appear in reports or presentations.

Method 1: Use savefig() to Save as PNG

The easy way to save a Matplotlib plot as a PNG is to use the savefig() function in Python. This method is built into Matplotlib and requires just a single line of code after plotting.

Here’s a quick example:

import matplotlib.pyplot as plt

# Sample data: Monthly sales in the USA (in thousands)
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun']
sales = [250, 270, 300, 280, 320, 310]

plt.plot(months, sales, marker='o')
plt.title('Monthly Sales in USA (in thousands)')
plt.xlabel('Month')
plt.ylabel('Sales')

# Save the plot as a PNG file
plt.savefig('monthly_sales.png')
plt.show()

You can see the output in the screenshot below.

save png python

What Happens Here?

  • After creating the plot, plt.savefig('monthly_sales.png') saves the figure directly to your current working directory.
  • The file format is automatically inferred from the file extension. Since we used .png, the image is saved as a PNG file.
  • You can open this PNG file with any image viewer or embed it in reports.

Method 2: Customize PNG Output with savefig() Parameters

Sometimes, the default PNG output isn’t enough. You might want to increase the resolution or add transparency to your image. Python savefig() function supports several parameters to help with this.

Here’s how I usually enhance the saved PNG:

plt.savefig('monthly_sales_highres.png', dpi=300, transparent=True, bbox_inches='tight')

You can see the output in the screenshot below.

matplotlib save image

Explanation of Parameters:

  • dpi=300: Sets the resolution to 300 dots per inch, making the image suitable for printing or high-quality presentations.
  • transparent=True: Saves the background as transparent instead of white, useful when overlaying images on colored backgrounds.
  • bbox_inches=’tight’: Automatically trims the whitespace around the plot, creating a cleaner image.

These options help tailor the PNG output to your specific needs.

Read Module ‘matplotlib’ has no attribute ‘plot’

Method 3: Save Multiple Plots as PNGs in a Loop

When working on projects with multiple charts, I often need to save several plots automatically. Here’s a quick way to save multiple figures as PNG files using a loop.

import matplotlib.pyplot as plt
import numpy as np

# Example: Daily temperatures in three US cities
cities = ['New York', 'Chicago', 'Los Angeles']
temperatures = {
    'New York': [30, 32, 35, 33, 31],
    'Chicago': [25, 28, 30, 29, 27],
    'Los Angeles': [60, 62, 65, 64, 63]
}
days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri']

for city in cities:
    plt.figure()
    plt.plot(days, temperatures[city], marker='s')
    plt.title(f'Daily Temperatures in {city}')
    plt.xlabel('Day')
    plt.ylabel('Temperature (°F)')

    filename = f'{city.lower().replace(" ", "_")}_temps.png'
    plt.savefig(filename, dpi=200)
    plt.close()

You can see the output in the screenshot below.

save matplotlib figure as png

Why Use plt.close()?

Calling plt.close() in Python, after saving the figure frees up memory, especially important when generating many plots in a script.

Check out Matplotlib xlim

Method 4: Save PNG Directly from Figure Object

If you prefer working with Figure objects explicitly, you can save the plot using the figure’s savefig() method.

fig, ax = plt.subplots()
ax.bar(months, sales, color='skyblue')
ax.set_title('Monthly Sales in USA (Bar Chart)')
ax.set_xlabel('Month')
ax.set_ylabel('Sales')

fig.savefig('monthly_sales_bar.png', dpi=250)

This method is handy when you want more control over figure properties or when working with multiple figures simultaneously.

Read Matplotlib Plot NumPy Array

Tips for Saving PNGs with Matplotlib

  • Set Figure Size Before Saving: Use plt.figure(figsize=(width, height)) to control the size of your plot in inches. This affects the output image size.
  plt.figure(figsize=(8, 5))
  • Use Tight Layout: Call plt.tight_layout() before saving to automatically adjust subplot parameters for a better fit.
  • Avoid Overwriting Files: Use descriptive filenames or timestamps to avoid overwriting existing PNGs.
  • Check Your Working Directory: By default, files are saved to your current working directory. Use absolute paths if needed.

Saving Matplotlib plots as PNG images is a fundamental skill for any Python developer working with data visualization. Whether you’re preparing charts for business meetings or embedding visuals in web apps, knowing how to save high-quality PNGs will enhance your workflow.

With the methods I’ve shared, you can easily save plots with customized resolution, transparency, and layout. Plus, automating the saving process for multiple plots can save you a lot of time.

If you want to explore further, Matplotlib supports other formats like PDF, SVG, and JPEG, but PNG remains the most versatile choice for most use cases.

Other Matplotlib articles you may also like:

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.