Save Plot to Image File Instead of Displaying It?

Better Stack Team
Updated on June 19, 2024

To save a plot to an image file instead of displaying it, you can use the savefig() function provided by the matplotlib.pyplot module. Here's how you can do it:

 
import matplotlib.pyplot as plt

# Generate some sample data and create a plot
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
plt.plot(x, y)

# Save the plot to an image file (e.g., PNG format)
plt.savefig('plot.png')

In this example:

  • We create a simple line plot using plt.plot().
  • We use plt.savefig('plot.png') to save the plot to an image file named plot.png in the current working directory.
  • You can specify the filename along with the desired file format (e.g., 'plot.png' for PNG format, 'plot.jpg' for JPEG format, etc.).
  • You can also specify additional parameters to control the size, resolution, and other properties of the saved image. For example, plt.savefig('plot.png', dpi=300) sets the resolution to 300 dots per inch (DPI).

After executing this code, the plot will be saved as an image file (plot.png in this example) in the current working directory.

Got an article suggestion? Let us know
Explore more
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

Make your mark

Join the writer's program

Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.

Write for us
Writer of the month
Marin Bezhanov
Marin is a software engineer and architect with a broad range of experience working...
Build on top of Better Stack

Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.

community@betterstack.com

or submit a pull request and help us build better products for everyone.

See the full list of amazing projects on github