Book Image

Applying Math with Python - Second Edition

By : Sam Morley
Book Image

Applying Math with Python - Second Edition

By: Sam Morley

Overview of this book

The updated edition of Applying Math with Python will help you solve complex problems in a wide variety of mathematical fields in simple and efficient ways. Old recipes have been revised for new libraries and several recipes have been added to demonstrate new tools such as JAX. You'll start by refreshing your knowledge of several core mathematical fields and learn about packages covered in Python's scientific stack, including NumPy, SciPy, and Matplotlib. As you progress, you'll gradually get to grips with more advanced topics of calculus, probability, and networks (graph theory). Once you’ve developed a solid base in these topics, you’ll have the confidence to set out on math adventures with Python as you explore Python's applications in data science and statistics, forecasting, geometry, and optimization. The final chapters will take you through a collection of miscellaneous problems, including working with specific data formats and accelerating code. By the end of this book, you'll have an arsenal of practical coding solutions that can be used and modified to solve a wide range of practical problems in computational mathematics and data science.
Table of Contents (13 chapters)

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.