Wednesday, October 2, 2024

How to save/export figure in Python ?

So far we have only created the plots and display them on the screen using the plt.show() function. However, the matplotlib has the ability to save (exprot) the created plots in various formats, and adjust the dots per inch number (quality) to obtain high-resolution images. \newline The Matplotlib plot can be saved by using the plt.savefig() function. The plt.savefig() function in deafult format is shown in the following code block.
matplotlib.pyplot.savefig(fname, *, transparent=None, dpi='figure', format=None,
metadata=None, bbox_inches=None, pad_inches=0.1,
facecolor='auto', edgecolor='auto', backend=None,
**kwargs
)
The matplotlib.pyplot.savefig() or plt.savefig() consist of the following parameters:
  • fname - is a str of file-like object type. The filename or file path where the figure is to be saved. It can be also a file-like object that supports the write mehtod. The file extension (.png, .pdf, .svg) determines the output format unless specified by the format argument.
  • transparent - is a bool type parameter and the default value is None. The parameter defines whether to make the background transparent. If the parameter is equal to True value the figure's patch and axes will be transparent. If the value is None, defaults to False for most formats and True for PDF and PS.
  • dpi - is a float type parameter or 'figure' and the default value is 'figure'. The resolution of the output in dots per inch (DPI). The default is the figure's DPI, which can be set when the figure is created (or default to the screen resolution).
  • format - is the str (string) type parameter, and the default value is None. The desired file format (e.g., 'png', 'pdf', 'svg', 'ps'). If not specified, the format is inferred from the filename extension.
  • metadata - is a dict type parameter and te default value is None. A dictionary containing metadata to include in the saved file. This is mainly useful for formats like PDF or PNG where metadata (such as author, title, etc.) can be embedded in the file.
  • bbox\_inches - is the str (String) parameter type or None. The default value is None. Controls the bounding box for the figure. The default behavior (None) saves the entire figure including the surrounding space. If set to 'tight', it attempts to reduce the amount of surrounding whitespace.
  • pad\_inches - is the float parameter type and the default value is 0.1. The amount of padding around the figure when bbox\_inches is set to 'tight'. It specifies how much space should be added around the edges of the saved figure.
  • facecolor - is a string type variable however, it can also be color or None, and the default value is "auto". The color of the figure’s background. The default ('auto') uses the figure. facecolor from the figure’s properties. A custom color can also be specified (e.g., 'white', '\#f2f2f2').
  • edgecolor - as the facecolor parameter a string type variable however, it can also be color or None, and the default value is "auto".The color of the edge of the figure. The default ('auto') uses the figure.edgecolor. Like facecolor, this can be customized.
  • bakcend - is a string (str) parameter type or None, and the default value is None.The backend used to render the figure. If not specified, the default backend for the figure is used.
  • kwargs - Additional parameters that are passed to the underlying backend or format-specific saving mechanisms. For example, you can pass compression settings for certain formats like PDF.
Inside the brackets you have to type the name with the file extension. Under this name + extension the matplotlib will be stored. For example:
plt.savefig("name.png")
It should be noted that in order to store the plot under this name the plt.show() function must be commented (using \#) or removed. Otherwise, if active, the plt.savefig will store empty figure under this name (in this case "name.png"). The other problem with this command is the quality of the figure. Since it is not defined the figure will have quality in terms of DPI (dots per inch) of 100. The matploltib figure can be saved in various formats and the most common are:
  • PNG,
  • JPG,
  • SVG, and
  • PDF.
To save the figure in the JPG format simply type the extension jpg after the figure name i.e. "name.jpg" in the plt.savefig() function. The following example shows how to save figure in the JPG format.
plt.figure(figsize=(12,8))
plt.plot(x,y)
plt.savefig("name.jpg")
To save the figure in the SVG format simply type the extension svg after the figure name i.e. "name.svg" in the plt.savefig() function. The following example shows how to save figure in the SVG format.
plt.figure(figsize=(12,8))
plt.plot(x,y)
plt.savefig("name.svg")
In case you want to save the figure in PDF format simply type the extension pdf after the figure name i.e. "name.pdf" in the plt.savefig() function.
plt.figure(figsize=(12,8))
plt.plot(x,y)
plt.savefig("name.pdf")
To change the quality of the exported figure you need to type the dpi = value as an argument in plt.savefig() function. In the following example we will created a simple plot that will be saved with 300 DPI.
plt.plot(x, y)
plt.savefig("my_plot.png")
plt.plot(x, y)
plt.savefig("high_res_plot.png", dpi=300)
The bbox\_inches parameter is also very important and useful. In case you have the legend outside the plot when you want to save the figure without defining the bbox\_inches parameter the saved figure will contain the plot while the legend will be cut out. To prevent this and to save the figure with plot and legend outside the plot you have to define the bbox\_inches and set the value to "tight".
plt.plot(x,y)
plt.savefig('my_plot.png", bbox_iches = 'tight')

No comments:

Post a Comment