Reader small image

You're reading from  Applying Math with Python - Second Edition

Product typeBook
Published inDec 2022
PublisherPackt
ISBN-139781804618370
Edition2nd Edition
Concepts
Right arrow
Author (1)
Sam Morley
Sam Morley
author image
Sam Morley

Sam Morley is an experienced lecturer in mathematics and a researcher in pure mathematics. He is currently a research software engineer at the University of Oxford working on the DataSig project. He was previously a lecturer in mathematics at the University of East Anglia and Nottingham Trent University. His research interests lie in functional analysis, especially Banach algebras. Sam has a firm commitment to providing high-quality, inclusive, and enjoyable teaching, with the aim of inspiring his students and spreading his enthusiasm for mathematics.
Read more about Sam Morley

Right arrow

Saving Matplotlib figures

When you work in an interactive environment, such as an IPython console or a Jupyter notebook, displaying a figure at runtime is perfectly normal. However, there are plenty of situations where it would be more appropriate to store a figure directly to a file, rather than rendering it on screen. In this recipe, we will see how to save a figure directly to a file, rather than displaying it on screen.

Getting ready

You will need the data to be plotted and the path or file object in which you wish to store the output. We store the result in savingfigs.png in the current directory. In this example, we will plot the following data:

x = np.arange(1, 5, 0.1)
y = x*x

Let’s see how to plot this curve using Matplotlib and save the resulting plot to a file (without needing to interact with the plot GUI).

How to do it...

The following steps show how to save a Matplotlib plot directly to a file:

  1. The first step is to create a figure, as usual, and add any labels, titles, and annotations that are necessary. The figure will be written to the file in its current state, so any changes to the figure should be made before saving:
    fig, ax = plt.subplots()
    ax.plot(x, y)
    ax.set_title("Graph of $y = x^2$", usetex=True)
    ax.set_xlabel("$x$", usetex=True)
    ax.set_ylabel("$y$", usetex=True)
  2. Then, we use the savefig method on fig to save this figure to a file. The only required argument is the path to output to or a file-like object that the figure can be written to. We can adjust various settings for the output format, such as the resolution, by providing the appropriate keyword arguments. We’ll set the Dots per Inch (DPI) of the output figure to 300, which is a reasonable resolution for most applications:
    fig.savefig("savingfigs.png", dpi=300)

Matplotlib will infer that we wish to save the image in the Portable Network Graphics (PNG) format from the extension of the file given. Alternatively, a format can be explicitly provided as a keyword argument (by using the format keyword), or it will fall back to the default from the configuration file.

How it works...

The savefig method chooses the appropriate backend for the output format and then renders the current figure in that format. The resulting image data is written to the specified path or file-like object. If you have manually created a Figure instance, the same effect can be achieved by calling the savefig method on that instance.

There’s more...

The savefig routine takes a number of additional optional keyword arguments to customize the output image. For example, the resolution of the image can be specified using the dpi keyword. The plots in this chapter have been produced by saving the Matplotlib figures to the file.

The output formats available include PNG, Scalable Vector Graphics (SVG), PostScript (PS), Encapsulated PostScript (EPS), and Portable Document Format (PDF). You can also save to JPEG format if the Pillow package is installed, but Matplotlib does not support this natively since version 3.1. There are additional customization keyword arguments for JPEG images, such as quality and optimize. A dictionary of image metadata can be passed to the metadata keyword, which will be written as image metadata when saving.

See also

The examples gallery on the Matplotlib website includes examples of embedding Matplotlib figures into a GUI application using several common Python GUI frameworks.

Previous PageNext Page
You have been reading a chapter from
Applying Math with Python - Second Edition
Published in: Dec 2022Publisher: PacktISBN-13: 9781804618370
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Sam Morley

Sam Morley is an experienced lecturer in mathematics and a researcher in pure mathematics. He is currently a research software engineer at the University of Oxford working on the DataSig project. He was previously a lecturer in mathematics at the University of East Anglia and Nottingham Trent University. His research interests lie in functional analysis, especially Banach algebras. Sam has a firm commitment to providing high-quality, inclusive, and enjoyable teaching, with the aim of inspiring his students and spreading his enthusiasm for mathematics.
Read more about Sam Morley