Перейти к содержимому

Как сохранить график в python matplotlib

  • автор:

Как сохранить рисунок Matplotlib в файл (с примерами)

Как сохранить рисунок Matplotlib в файл (с примерами)

Вы можете использовать следующий базовый синтаксис для сохранения рисунка Matplotlib в файл:

В следующих примерах показано, как использовать этот синтаксис на практике.

Пример 1: сохранить рисунок Matplotlib в файл PNG

Следующий код показывает, как сохранить фигуру Matplotlib в файл PNG:

Если мы перейдем к месту, где мы сохранили файл, мы сможем просмотреть его:

Пример 2: сохранить рисунок Matplotlib с плотным макетом

По умолчанию Matplotlib добавляет щедрые отступы вокруг рисунка.

Чтобы удалить это дополнение, мы можем использовать аргумент bbox_inches=’tight’ :

Обратите внимание, что снаружи графика меньше отступов.

Пример 3: сохранить рисунок Matplotlib с нестандартным размером

Вы также можете использовать аргумент dpi , чтобы увеличить размер рисунка Matplotlib при его сохранении:

Полную онлайн-документацию по функции savefig() в Matplotlib можно найти здесь .

Дополнительные ресурсы

В следующих руководствах объясняется, как выполнять другие распространенные функции в Matplotlib:

Save a Plot to a File in Matplotlib (using 14 formats)

The Matplotlib is a popular plotting library for Python. It can be used in Python scripts and Jupyter Notebooks. The plot can be displayed in a separate window or a notebook. What if you would like to save the plot to a file? In this article, I will show you how to save the Matplotlib plot into a file. It can be done by using 14 different formats.

Quick code snippet

Below is a quick Python code snippet that shows how to save a figure to a file.

Important:

  1. Please call plt.show() after plt.savefig() . Otherwise, you will get an empty plot in the file.
  2. For Jupyter Notebook users, you need to call plt.savefig() in the same cell in which the plot is created. Otherwise, the file has an empty figure.

The savefig function — deep dive

All plots created with Matplotlib are saved with savefig function. Please take a while a look into savefig documentation.

Below are savefig arguments that you might find useful:

  • fname — a path where to save a plot. It can be without extension. For fname with the extension included the format will be automatically selected. Common extensions: .png , .pdf , .svg ;
  • dpi — a numeric value for dots per inch; it controls the size of the figure in pixels. You can read more in an article on how to change figure size in Matplotlib ;
  • bbox_inches — controls the white space around the figure, if you don’t need margins, please set this parameter to tight ;
  • transparent — is a boolean value that can turn the plot background into transparent;
  • format — is a string with the output file format. Common formats are png , pdf , svg . If not specified, it is automatically set from the fname extension. The default is png .

You can list all available formats in Matplotlib with below Python code:

There are, in total 13 formats supported by Matplotlib .

matplotlib plots save to different file formats

Example of advanced save

Let’s try to save a figure to PNG format with transparent background with a size of 1200×800 pixels:

We set the size of the figure during creation, the size in pixels is computed by multiplying figsize by dpi .

matplotlib plot

Save Matplotlib figure

Earlier, we save plots in graphics formats. What if we would like to save the whole Matplotlib figure for further manipulation? It is possible. We can use the pickle library. It is a Python object serialization package. It doesn’t need to be installed additionally.

Here is an example Python code that creates the Matplitlib figure, saves to a file, and loads it back:

Summary

You can save the Matplotlib plot to a file using 13 graphics formats. The most common formats are .png , .pdf , .svg and .jpg . The savefig() function has useful arguments: transparent , bbox_inches , or format . There is an option to serialize the figure object to a file and load it back with the pickle package. It can be used to save the figure for future manipulations.

matplotlib.pyplot.savefig#

The available output formats depend on the backend being used.

Parameters : fname str or path-like or binary file-like

A path, or a Python file-like object, or possibly some backend-dependent object such as matplotlib.backends.backend_pdf.PdfPages .

If format is set, it determines the output format, and the file is saved as fname. Note that fname is used verbatim, and there is no attempt to make the extension, if any, of fname match format, and no extension is appended.

If format is not set, then the format is inferred from the extension of fname, if there is one. If format is not set and fname has no extension, then the file is saved with rcParams["savefig.format"] (default: ‘png’ ) and the appropriate extension is appended to fname.

Other Parameters : dpi float or ‘figure’, default: rcParams["savefig.dpi"] (default: ‘figure’ )

The resolution in dots per inch. If ‘figure’, use the figure’s dpi value.

format str

The file format, e.g. ‘png’, ‘pdf’, ‘svg’, . The behavior when this is unset is documented under fname.

metadata dict, optional

Key/value pairs to store in the image metadata. The supported keys and defaults depend on the image format and backend:

‘png’ with Agg backend: See the parameter metadata of print_png .

‘pdf’ with pdf backend: See the parameter metadata of PdfPages .

‘svg’ with svg backend: See the parameter metadata of print_svg .

‘eps’ and ‘ps’ with PS backend: Only ‘Creator’ is supported.

Bounding box in inches: only the given portion of the figure is saved. If ‘tight’, try to figure out the tight bbox of the figure.

pad_inches float, default: rcParams["savefig.pad_inches"] (default: 0.1 )

Amount of padding around the figure when bbox_inches is ‘tight’.

facecolor color or ‘auto’, default: rcParams["savefig.facecolor"] (default: ‘auto’ )

The facecolor of the figure. If ‘auto’, use the current figure facecolor.

edgecolor color or ‘auto’, default: rcParams["savefig.edgecolor"] (default: ‘auto’ )

The edgecolor of the figure. If ‘auto’, use the current figure edgecolor.

backend str, optional

Use a non-default backend to render the file, e.g. to render a png file with the "cairo" backend rather than the default "agg", or a pdf file with the "pgf" backend rather than the default "pdf". Note that the default backend is normally sufficient. See The builtin backends for a list of valid backends for each file format. Custom backends can be referenced as "module://. ".

orientation

Currently only supported by the postscript backend.

papertype str

One of ‘letter’, ‘legal’, ‘executive’, ‘ledger’, ‘a0’ through ‘a10’, ‘b0’ through ‘b10’. Only supported for postscript output.

transparent bool

If True, the Axes patches will all be transparent; the Figure patch will also be transparent unless facecolor and/or edgecolor are specified via kwargs.

If False has no effect and the color of the Axes and Figure patches are unchanged (unless the Figure patch is specified via the facecolor and/or edgecolor keyword arguments in which case those colors are used).

The transparency of these patches will be restored to their original values upon exit of this function.

This is useful, for example, for displaying a plot on top of a colored background on a web page.

bbox_extra_artists list of Artist , optional

A list of extra artists that will be considered when the tight bbox is calculated.

Matplotlib – Save Plot as a File

Matplotlib is a library in python that offers a number of plotting options to display your data. The plots created get displayed when you use plt.show() but you cannot access them later since they’re not saved on disk. In this tutorial, we’ll look at how to save a matplotlib plot as an image file.

How to save a matplotlib plot as an image file?

To save a figure created with matplotlib, you can use pyplot’s savefig() function. This way, you’ll have the plots saved on disk for further use instead of having to plot them all over again. The following is the syntax:

Pass the path where you want the image to be saved. The savefig() function also comes with a number of additional parameters to further customize how your image gets saved.

Examples

Let’s look at some examples of using plt.savefig() to save a maplotlib figure.

1. Save a plot to an image file

Let’s say you have the data of some of NBA’s greatest basketball players’ championship title counts and you want to plot it as a bar chart. Furthermore, you want to save it as an image so that you can use it later (for example, in a presentation)

This saves the bar chart as a PNG file with the name NBA_bar_chart.png to the current directory. You can specify the path and name of your image as per your needs. This is how the saved plot looks on opening it with an image viewer application:

Bar chart saved on disk opened with the Photos application in Windows

2. Save plot as a PDF

Depending on the filename provided plt.savefig() infers the format of the output file. For instance, if you want to save the above image as a PDF file, just use the appropriate file name:

The above code saves the plot as a PDF file with the name NBA_bar_chart_doc.pdf to the current directory. This is how the saved images looks like on opening it in Google Chrome web browser:

Matplotlib plot saved as a pdf file opened in chrome

For more on the plt.savefig() function, refer to its documentation.

With this, we come to the end of this tutorial. The code examples and results presented in this tutorial have been implemented in a Jupyter Notebook with a python (version 3.8.3) kernel having matplotlib version 3.2.2

Tutorials on matplotlib –

Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *