What is the function of plt.savefig in Python?

The plt.savefig() function is a method in the Matplotlib library used to save the current plot as a file.

To be specific, the plt.savefig() function allows users to save the currently opened graph in common image formats such as PNG, JPEG, SVG, etc. The syntax of this function is as follows:

plt.savefig(fname, dpi=None, format=None, **kwargs)

Explanation of parameters:

  1. The file name or path of the saved document.
  2. DPI: an optional parameter that specifies the resolution at which the image is saved.
  3. Format: an optional parameter that specifies the image format to be saved. If not specified, it will be automatically determined based on the file extension.
  4. kwargs: Additional optional parameters to be passed to the underlying image library options.

Before calling the plt.savefig() function, it is important to first create and display the graph on the screen. Afterwards, use plt.savefig() to save the plot.

Here is an example showing how to save a plot created with Matplotlib using plt.savefig().

import matplotlib.pyplot as plt

# 创建并绘制一个简单的图形
x = [1, 2, 3, 4, 5]
y = [1, 4, 9, 16, 25]
plt.plot(x, y)

# 保存图形为PNG格式
plt.savefig('plot.png')

# 保存图形为JPEG格式,指定分辨率为300dpi
plt.savefig('plot.jpg', dpi=300)

After executing the above code, two files named plot.png and plot.jpg will be generated in the current working directory, each saving the plotted graph.

bannerAds