Python Friday #166: Export your Matplotlib Plots

Creating plots in Matplotlib is fun. But when we only can use the visualisations inside our Jupyter notebook we cannot fully benefit from our work. Let us change that and export our plots into various formats.

This post is part of my journey to learn Python. You can find the other parts of this series here. You find the code for this post in my PythonFriday repository on GitHub.

 

Supported formats

Matplotlib let us export figures in various formats. We can get the list of supported formats with the method canvas.get_supported_filetypes() of our figure:

{‘eps’: ‘Encapsulated Postscript’,
‘jpg’: ‘Joint Photographic Experts Group’,
‘jpeg’: ‘Joint Photographic Experts Group’,
‘pdf’: ‘Portable Document Format’,
‘pgf’: ‘PGF code for LaTeX’,
‘png’: ‘Portable Network Graphics’,
‘ps’: ‘Postscript’,
‘raw’: ‘Raw RGBA bitmap’,
‘rgba’: ‘Raw RGBA bitmap’,
‘svg’: ‘Scalable Vector Graphics’,
‘svgz’: ‘Scalable Vector Graphics’,
‘tif’: ‘Tagged Image File Format’,
‘tiff’: ‘Tagged Image File Format’,
‘webp’: ‘WebP Image Format’}

 

Setup code

To be a bit more specific where we save our images, we can define a folder for our image export. As with code and data, we can set it relative to our notebook:

 

Export a figure

We can save a figure into a file with this command:

Since we choose *.jpg as its filename ending, Matplotlib saves the figure as a JPG. If we want to store it as an SVG file, we can use *.svg as the filename suffix:

We can call the savefig() method with a few arguments. While transparent (for the background) and dpi (the resolution) are understandable, bbox_inches stands for bounding box in inches. This parameter allows us to set the space around our figure in inches or we can use “tight” and Matplotlib finds a value that gives us only a small border around the figure.

The figure with no specified bbox_inches looks like this:

There is a wider space between our figure and the edge of the image

While bbox_inches=”tight” gives us this tight spacing:

The image is only slightly larger than the figure

 

Next

With the savefig() method we can export our plot in JupyterLab into a common file that we can share and use in other applications. Next week we explore different ways to visualise our data in Matplotlib.

1 thought on “Python Friday #166: Export your Matplotlib Plots”

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.