How to Save Matplotlib Plot to a File Instead of Displaying It?

python

To save a Matplotlib plot to a file instead of displaying it, you can use the savefig() function. The savefig() function allows you to save the current figure to a file in a variety of formats, including PNG, PDF, SVG, and more.

Here's a simple example of how to save a Matplotlib plot to a PNG file:

import matplotlib.pyplot as plt

# Create a plot
x = [1, 2, 3, 4]
y = [1, 4, 2, 3]
plt.plot(x, y)

# Save the plot to a file
plt.savefig('my_plot.png')

In this example, we first create a simple plot using the plot() function. Then, we use the savefig() function to save the plot to a file named my_plot.png.

You can also specify various options when saving the plot, such as the file format, the resolution, and more. Here's an example:

import matplotlib.pyplot as plt

# Create a plot
x = [1, 2, 3, 4]
y = [1, 4, 2, 3]
plt.plot(x, y)

# Save the plot to a file
plt.savefig('my_plot.pdf', dpi=300, bbox_inches='tight')

In this example, we save the plot to a PDF file with a resolution of 300 DPI and use the bbox_inches parameter to ensure that the plot is saved with minimal whitespace around the edges.

Note that you should call savefig() before calling show() or close() to avoid saving a blank image.

Latest Questions

python How to Fix ""zsh: command not found: python" Error on MacOS X? python How to Fix "xlrd.biffh.XLRDError: Excel xlsx file; not supported" Error in Pandas? python How to Remove All Whitespace From a Python String?