I'm confused about the role played by the backend used by matplotlib in determining what formats can be rendered.
For example, the documentation says that the 'agg' backend generates PNG, "raster 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 generate a PDF, or
fig.savefig(“thefig.svg”)
to produce vector graphics.
What role does the backend play in limiting what formats and kinds of rendering (vector vs. raster) matplotlib can produce?
Good question! The Agg
backend itself only produces raster graphics.
What's happening when you call fig.savefig('name.pdf')
(or .svg
) 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 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 asked to save a raster image.
Switching backends can be done on the fly for non-interactive backends, so this technique is used extensively "behind-the-scenes" to allow figures to be saved in multiple formats.
A bit more detail, in case you're ever writing a matplotlib backend: Any matplotlib Canvas 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 saving in general. Saving to a specific format is handled by looking up the approriate print_<formatname>
method (See FigureCanvasBase._get_print_method
for exact details).
Each backend specifies which formats it can save to by overriding those methods. The default for each is to temporarily switch back to the relevant "base" backend (e.g. Agg for raster formats, PDF for pdf, SVG for svg, etc). This allows figures to be easily saved to all formats even if the backend you're using only supports a single format.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With