What are the limitations of the matplotlib backend in rendering formats?

I got confused about the role that the backend plays, used by matplotlib in determining which formats can be displayed.

For example, the documentation says that the β€œagg” backend generates PNG, β€œbitmap graphics,” but if I

import matplotlib matplotlib.use('agg') import matplotlib.pyplot fig, ax = matplotlib.pyplot.subplots() #... 

I can use

 fig.savefig("thefig.pdf") 

to create a pdf file or

 fig.savefig("thefig.svg") 

to create vector graphics.

What role does the backend play in limiting what formats and types of rendering (vector or raster) matplotlib can create?

+5
source share
1 answer

Good question! The Agg server Agg creates only raster graphics.

What happens when fig.savefig('name.pdf') (or .svg ) is called is that the backend is temporarily changed to generate vector output.

Each backend can choose how it handles this, but for Agg , when you save the vector output, it basically does:

 pdf = self.switch_backends(FigureCanvasPdf) return pdf.print_pdf(*args, **kwargs) 

Similarly, for the PDF backend, it temporarily switches to Agg if it is asked to save the bitmap.

Switching backends can be done on the fly for non-interactive backends, which is why this method is widely used behind the scenes to allow you to save shapes in several formats.


A bit more detailed if you have ever written a matplotlib backend: Any Canplat matplotlib instance has several print_<format> methods:

 In [24]: backend_bases.FigureCanvasBase.print_<tab> backend_bases.FigureCanvasBase.print_bmp backend_bases.FigureCanvasBase.print_eps backend_bases.FigureCanvasBase.print_figure backend_bases.FigureCanvasBase.print_jpeg backend_bases.FigureCanvasBase.print_jpg backend_bases.FigureCanvasBase.print_pdf backend_bases.FigureCanvasBase.print_pgf backend_bases.FigureCanvasBase.print_png backend_bases.FigureCanvasBase.print_ps backend_bases.FigureCanvasBase.print_raw backend_bases.FigureCanvasBase.print_rgba backend_bases.FigureCanvasBase.print_svg backend_bases.FigureCanvasBase.print_svgz backend_bases.FigureCanvasBase.print_tif backend_bases.FigureCanvasBase.print_tiff 

The print_figure method controls the whole save. Saving in a specific format is handled by looking for the aptoriate print_<formatname> method (see FigureCanvasBase._get_print_method for exact details).

Each backend determines which formats it can save by overriding these methods. By default, for each of them, it is necessary to temporarily return to the corresponding base server (for example, Agg for raster formats, PDF for PDF, SVG for svg, etc.). This makes it easy to save shapes in all formats, even if your backend supports only one format.

+2
source

Source: https://habr.com/ru/post/1205979/


All Articles