Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Applying Math with Python
Applying Math with Python

Applying Math with Python: Over 70 practical recipes for solving real-world computational math problems , Second Edition

eBook
€26.98 €29.99
Paperback
€37.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Applying Math with Python

Mathematical Plotting with Matplotlib

Plotting is a fundamental tool in all of mathematics. A good plot can reveal hidden details, suggest future directions, verify results, or reinforce an argument. It is no surprise, then, that the scientific Python stack features a powerful and flexible plotting library called Matplotlib.

In this chapter, we will plot functions and data in a variety of styles and create figures that are fully labeled and annotated. We will create three-dimensional plots, customize the appearance of figures, create figures that contain multiple plots using subplots, and save figures directly to files for applications that are not running in an interactive environment.

Plotting is one of the most important aspects covered in this book. Plotting data, functions, or solutions can often help you gain an understanding of a problem that can really help to reason about your methods. We will see plotting again in every chapter of this book.

In this chapter, we will cover the following recipes:

  • Basic plotting with Matplotlib
  • Adding subplots
  • Plotting with error bars
  • Saving Matplotlib figures
  • Surface and contour plots
  • Customizing three-dimensional plots
  • Plotting vector fields with quiver plots

Technical requirements

The main plotting package for Python is Matplotlib, which can be installed using your favorite package manager, such as pip:

python3.10 -m pip install matplotlib

This will install the most recent version of Matplotlib, which, at the time of writing this book, is version 3.5.2.

Matplotlib contains numerous sub-packages, but the main user interface (UI) is the matplotlib.pyplot package, which, by convention, is imported under the plt alias. This is achieved using the following import statement:

import matplotlib.pyplot as plt

Many of the recipes in this chapter also require NumPy, which, as usual, is imported under the np alias.

The code for this chapter can be found in the Chapter 02 folder of the GitHub repository at https://github.com/PacktPublishing/Applying-Math-with-Python-2nd-Edition/tree/main/Chapter%2002.

Basic plotting with Matplotlib

Plotting is an important part of understanding behavior. So much can be learned by simply plotting a function or data that would otherwise be hidden. In this recipe, we will walk through how to plot simple functions or data using Matplotlib, set the plotting style, and add labels to a plot.

Matplotlib is a very powerful plotting library, which means it can be rather intimidating to perform simple tasks with it. For users who are used to working with MATLAB and other mathematical software packages, there is a state-based interface called pyplot. There is also an object-oriented interface (OOI), which might be more appropriate for more complex plots. In either case, the pyplot interface is a convenient way to create basic objects.

Getting ready

Most commonly, the data that you wish to plot will be stored in two separate NumPy arrays, which we will label x and y for clarity (although this naming does not matter in practice). We will demonstrate plotting the graph of a function, so we will generate an array of x values and use the function to generate the corresponding y values. We’re going to plot three different functions over the range on the same axes:

def f(x):
  return x*(x - 2)*np.exp(3 – x)
def g(x):
  return x**2
def h(x):
  return 1 - x

Let’s plot these three functions in Python using Matplotlib.

How to do it...

Before we can plot the function, we must generate x and y data to be plotted. If you are plotting existing data, you can skip these commands. We need to create a set of x values that cover the desired range, and then use the function to create y values:

  1. The linspace routine from NumPy is ideal for creating arrays of numbers for plotting. By default, it will create 50 equally spaced points between the specified arguments. The number of points can be customized by providing an additional argument, but 50 is sufficient for most cases:
    x = np.linspace(-0.5, 3.0)  # 50 values between -0.5 and 3.0
  2. Once we have created x values, we can generate y values:
    y1 = f(x)  # evaluate f on the x points
    y2 = g(x)  # evaluate g on the x points
    y3 = h(x)  # evaluate h on the x points
  3. To plot the data, we first need to create a new figure and attach axes objects, which can be achieved by calling the plt.subplots routine without any arguments:
    fig, ax = plt.subplots()

Now, we use the plot method on the ax object to plot the first function. The first two arguments are and coordinates to be plotted, and the third (optional) argument specifies that the line color should be black:

ax.plot(x, y1, "k")  # black solid line style

To help distinguish the plots for the other functions, we plot those with a dashed line and a dot-dash line:

ax.plot(x, y2, "k--")  # black dashed line style
ax.plot(x, y3, "k.-")  # black dot-dashed line style

Every plot should have a title and axis labels. In this case, there isn’t anything interesting to label the axes with, so we just label them "x" and "y":

ax.set_title("Plot of the functions f, g, and h")
ax.set_xlabel("x")
ax.set_ylabel("y")

Let’s also add a legend to help you distinguish between the different function plots without having to look elsewhere to see which line is which:

ax.legend(["f", "g", "h"])

Finally, let’s annotate the plot to mark the intersection between the functions and with text:

ax.text(0.4, 2.0, "Intersection")

This will plot the y values against the x values on a new figure. If you are working within IPython or with a Jupyter notebook, then the plot should automatically appear at this point; otherwise, you might need to call the plt.show function to make the plot appear:

plt.show()

If you use plt.show, the figure should appear in a new window. We won’t add this command to any further recipes in this chapter, but you should be aware that you will need to use it if you are not working in an environment where plots will be rendered automatically, such as an IPython console or a Jupyter Notebook. The resulting plot should look something like the plot in Figure 2.1:

Figure 2.1 – Three functions on a single set of axes, each with a different style, with labels, legend, and an annotation

Figure 2.1 – Three functions on a single set of axes, each with a different style, with labels, legend, and an annotation

Note

If you are using a Jupyter notebook and the subplots command, you must include the call to subplots within the same cell as the plotting commands or the figure will not be produced.

How it works…

Here, we’re using the OOI because it allows us to keep track of exactly which figure and axes object we’re plotting on. This isn’t so important here where we have only a single figure and axes, but one can easily envisage situations where you might have two or more figures and axes concurrently. Another reason to follow this pattern is to be consistent when you add multiple subplots—see the Adding subplots recipe.

You can produce the same plot as in the recipe via the state-based interface by using the following sequence of commands:

plt.plot(x, y1, "k", x, y2, "k--", x, y3, "k.-")
plt.title("Plot of the functions f, g, and h")
plt.xlabel("x")
plt.ylabel("y")
plt.legend(["f", "g", "h"])
plt.text(0.4, 2.0, "Intersection")

If there are currently no Figure or Axes objects, the plt.plot routine creates a new Figure object, adds a new Axes object to the figure, and populates this Axes object with the plotted data. A list of handles to the plotted lines is returned. Each of these handles is a Lines2D object. In this case, this list will contain a single Lines2D object. We could use this Lines2D object to further customize the appearance of the line later.

Notice that in the preceding code, we combined all the calls to the plot routine together. This is also possible if you use the OOI; the state-based interface is passing the arguments to the axes method on the set of axes that it either retrieves or creates.

The object layer of Matplotlib interacts with a lower-level backend, which does the heavy lifting of producing the graphical plot. The plt.show function issues an instruction to the backend to render the current figure. There are a number of backends that can be used with Matplotlib, which can be customized by setting the MPLBACKEND environment variable, modifying the matplotlibrc file, or by calling matplotlib.use from within Python with the name of an alternative backend. By default, Matplotlib picks a backend that is appropriate for the platform (Windows, macOS, Linux) and purpose (interactive or non-interactive), based on which backends are available. For example, on the author’s system, the QtAgg backend is the default. This is an interactive backend based on the Anti-Grain Geometry (AGG) library. Alternatively, one might want to use the QtCairo backend, which uses the Cairo library for rendering.

Note

The plt.show function does more than simply call the show method on a figure. It also hooks into an event loop to correctly display the figure. The plt.show routine should be used to display a figure, rather than the show method on a Figure object.

The format string used to quickly specify the line style has three optional parts, each consisting of one or more characters. The first part controls the marker style, which is the symbol that is printed at each data point; the second controls the style of the line that connects the data points; the third controls the color of the plot. In this recipe, we only specified the line style. However, one could specify both line style and marker style or just marker style. If you only provide the marker style, no connecting lines are drawn between the points. This is useful for plotting discrete data where no interpolation between points is necessary.

Four line-style parameters are available: a solid line (-), a dashed line (--), a dash-dot line (-.), or a dotted line (:). Only a limited number of colors can be specified in the format string; they are red, green, blue, cyan, yellow, magenta, black, and white. The character used in the format string is the first letter of each color (with the exception of black), so the corresponding characters are r, g, b, c, y, m, k, and w, respectively.

In the recipe, we saw three examples of these format strings: the single k format string only changed the color of the line and kept the other settings at default (small point markers and unbroken blue line); the k-- and k.- format strings both changed the color and the line style. For an example of changing the point style, see the There’s more... section and Figure 2.2:

Figure 2.2 - Plot of three sets of data, each plotted using a different marker style

Figure 2.2 - Plot of three sets of data, each plotted using a different marker style

The set_title, set_xlabel, and set_ylabel methods simply add the text argument to the corresponding position of the Axes object. The legend method, as called in the preceding code, adds the labels to the datasets in the order that they were added to the plot—in this case, y1, y2, and then y3.

There are a number of keyword arguments that can be supplied to the set_title, set_xlabel, and set_ylabel routines to control the style of the text. For example, the fontsize keyword can be used to specify the size of the label font in the usual pt point measure.

The annotate method on the Axes object adds arbitrary text to a specific position on the plot. This routine takes two arguments—the text to display as a string and the coordinates of the point at which the annotation should be placed. This routine also accepts keyword arguments that can be used to customize the style of the annotation.

There’s more…

The plt.plot routine accepts a variable number of positional inputs. In the preceding code, we supplied two positional arguments that were interpreted as x values and y values (in that order). If we had instead provided only a single array, the plot routine would have plotted the values against their position in the array; that is, the x values are taken to be 0, 1, 2, and so on.

The plot method also accepts a number of keyword arguments that can also be used to control the style of a plot. Keyword arguments take precedence over format string parameters if both are present, and they apply to all sets of data plotted by the call. The keyword to control the marker style is marker, the keyword for the line style is linestyle, and the keyword for color is color. The color keyword argument accepts a number of different formats to specify a color, which includes RGB values as a (r, g, b) tuple, where each character is a float between 0 and 1 or is a hex string. The width of the line plotted can be controlled using the linewidth keyword, which should be provided with a float value. Many other keyword arguments can be passed to plot; a list is given in the Matplotlib documentation. Many of these keyword arguments have a shorter version, such as c for color and lw for linewidth.

In the this recipe, we plotted a large number of coordinates generated by evaluating functions on a selection of values. In other applications, one might have data sampled from the real world (as opposed to generated). In these situations, it might be better to leave out the connecting lines and simply plot the markers at the points. Here is an example of how this might be done:

y1 = np.array([1.0, 2.0, 3.0, 4.0, 5.0])
y2 = np.array([1.2, 1.6, 3.1, 4.2, 4.8])
y3 = np.array([3.2, 1.1, 2.0, 4.9, 2.5])
fig, ax = plt.subplots()
ax.plot(y1, 'o', y2, 'x', y3, '*', color="k")

The result of these commands is shown in Figure 2.2. Matplotlib has a specialized method for producing scatter plots such as this, called scatter.

Other aspects of the plot can be customized by using methods on the Axes object. The axes ticks can be modified using the set_xticks and set_yticks methods on the Axes object, and the grid appearance can be configured using the grid method. There are also convenient methods in the pyplot interface that apply these modifications to the current axes (if they exist).

For example, we modify the axis limits, set the ticks at every multiple of 0.5 in both the and direction, and add a grid to the plot by using the following commands:

ax.axis([-0.5, 5.5, 0, 5.5]) # set axes
ax.set_xticks([0.5*i for i in range(9)])  # set xticks
ax.set_yticks([0.5*i for i in range(11)]) # set yticks
ax.grid()  # add a grid

Notice how we set the limits slightly larger than the extent of the plot. This is to avoid markers being placed on the boundary of the plot window.

Matplotlib has many other plotting routines besides the plot routine described here. For example, there are plotting methods that use a different scale for the axes, including the logarithmic or axes separately (semilogx or semilogy, respectively) or together (loglog). These are explained in the Matplotlib documentation. The scatter plotting routine may be useful if you wish to plot discrete data on axes without connecting the points with a line. This allows more control over the style of the marker. For example, you can scale the marker according to some additional information.

We can use a different font by using the fontfamily keyword, the value of which can be the name of a font or serif, sans-serif, or monospace, which will choose the appropriate built-in font. A complete list of modifiers can be found in the Matplotlib documentation for the matplotlib.text.Text class.

Text arguments can also be rendered using TeX for additional formatting by supplying usetex=True to the routine. We’ll demonstrate the use of TeX formatting of labels in Figure 2.3 in the following recipe. This is especially useful if the title or axis label contains a mathematical formula. Unfortunately, the usetex keyword argument cannot be used if TeX is not installed on the system—it will cause an error in this case. However, it is still possible to use the TeX syntax for formatting mathematical text within labels, but this will be typeset by Matplotlib, rather than by TeX.

Adding subplots

Occasionally, it is useful to place multiple related plots within the same figure side by side but not on the same axes. Subplots allow us to produce a grid of individual plots within a single figure. In this recipe, we will see how to create two plots side by side on a single figure using subplots.

Getting ready

You will need the data to be plotted on each subplot. As an example, we will plot the first five iterates of Newton’s method applied to the function with an initial value of on the first subplot, and for the second, we will plot the error of the iterate. We first define a generator function to get the iterates:

def generate_newton_iters(x0, number):
  iterates = [x0]
  errors = [abs(x0 - 1.)]
  for _ in range(number):
       x0 = x0 - (x0*x0 - 1.)/(2*x0)
       iterates.append(x0)
       errors.append(abs(x0 - 1.))
    return iterates, errors

This routine generates two lists. The first list contains iterates of Newton’s method applied to the function, and the second contains the error in the approximation:

iterates, errors = generate_newton_iters(2.0, 5)

How to do it...

The following steps show how to create a figure that contains multiple subplots:

  1. We use the subplots routine to create a new figure and references to all of the Axes objects in each subplot, arranged in a grid with one row and two columns. We also set the tight_layout keyword argument to True to fix the layout of the resulting plots. This isn’t strictly necessary, but it is in this case as it produces a better result than the default:
    fig, (ax1, ax2) = plt.subplots(1, 2, 
    tight_layout=True) 
    #1 row, 2 columns
  2. Once Figure and Axes objects are created, we can populate the figure by calling the relevant plotting method on each Axes object. For the first plot (displayed on the left), we use the plot method on the ax1 object, which has the same signature as the standard plt.plot routine. We can then call the set_title, set_xlabel, and set_ylabel methods on ax1 to set the title and the x and y labels. We also use TeX formatting for the axes labels by providing the usetex keyword argument; you can ignore this if you don’t have TeX installed on your system:
    ax1.plot(iterates, "kx")
    ax1.set_title("Iterates")
    ax1.set_xlabel("$i$", usetex=True)
    ax1.set_ylabel("$x_i$", usetex=True)
  3. Now, we can plot the error values on the second plot (displayed on the right) using the ax2 object. We use an alternative plotting method that uses a logarithmic scale on the axis, called semilogy. The signature for this method is the same as the standard plot method. Again, we set the axes labels and the title. Again, the use of usetex can be left out if you don’t have TeX installed:
    ax2.semilogy(errors, "kx") # plot y on logarithmic scale
    ax2.set_title("Error")
    ax2.set_xlabel("$i$", usetex=True)
    ax2.set_ylabel("Error")

The result of this sequence of commands is shown here:

Figure 2.3 - Multiple subplots on the same Matplotlib figure

Figure 2.3 - Multiple subplots on the same Matplotlib figure

The left-hand side plots the first five iterates of Newton’s method, and the right-hand side is the approximation error plotted on a logarithmic scale.

How it works...

A Figure object in Matplotlib is simply a container for plot elements, such as Axes, of a certain size. A Figure object will usually only hold a single Axes object, which occupies the entire figure area, but it can contain any number of Axes objects in the same area. The subplots routine does several things. It first creates a new figure and then creates a grid with the specified shape in the figure area. Then, a new Axes object is added to each position of the grid. The new Figure object and one or more Axes objects are then returned to the user. If a single subplot is requested (one row and one column, with no arguments) then a plain Axes object is returned. If a single row or column is requested (with more than one column or row, respectively), then a list of Axes objects is returned. If more than one row and column are requested, a list of lists, with rows represented by inner lists filled with Axes objects, will be returned. We can then use the plotting methods on each of the Axes objects to populate the figure with the desired plots.

In this recipe, we used the standard plot method for the left-hand side plot, as we have seen in previous recipes. However, for the right-hand side plot, we used a plot where the axis had been changed to a logarithmic scale. This means that each unit on the axis represents a change of a power of 10 rather than a change of one unit so that 0 represents , 1 represents 10, 2 represents 100, and so on. The axes labels are automatically changed to reflect this change in scale. This type of scaling is useful when the values change by an order of magnitude, such as the error in an approximation, as we use more and more iterations. We can also plot with a logarithmic scale for only by using the semilogx method, or both axes on a logarithmic scale by using the loglog method.

There’s more...

There are several ways to create subplots in Matplotlib. If you have already created a Figure object, then subplots can be added using the add_subplot method of the Figure object. Alternatively, you can use the subplot routine from matplotlib.pyplot to add subplots to the current figure. If one does not yet exist, it will be created when this routine is called. The subplot routine is a convenience wrapper of the add_subplot method on the Figure object.

In the preceding example, we created two plots with differently scaled axes. This demonstrates one of the many possible uses of subplots. Another common use is for plotting data in a matrix where columns have a common x label and rows have a common y label, which is especially common in multivariate statistics when investigating the correlation between various sets of data. The plt.subplots routine for creating subplots accepts the sharex and sharey keyword parameters, which allows the axes to be shared among all subplots or among a row or column. This setting affects the scale and ticks of the axes.

See also

Matplotlib supports more advanced layouts by providing the gridspec_kw keyword arguments to the subplots routine. See the documentation for matplotlib.gridspec for more information.

Plotting with error bars

It is quite common that the values that we gather from the real world carry some uncertainty; no measurement of a real-world quantity is perfectly accurate. For example, if we measure a distance with a tape measure, there is a certain amount of accuracy that we can assume in our results, but beyond this accuracy, we cannot be sure that our measurement is valid. For such a situation, we can probably be confident of our accuracy up to about 1 millimeter or a little less than 1/16 inch. (This is, of course, assuming that we are measuring perfectly.) These values are the smallest subdivisions on typical tape measures. Let’s assume that we have collected such a set of 10 measurements (in centimeters) and we wish to plot these values along with the accuracy that we are confident about. (The range of values that lie above or below the measurement by the accuracy amount is called the error.) This is what we address in this recipe.

Getting ready

As usual, we have the Matplotlib pyplot interface imported under the alias plt. We first need to generate our hypothetical data and the assumed accuracy in NumPy arrays:

measurement_id = np.arange(1, 11)
measurements = np.array([2.3, 1.9, 4.4, 1.5, 3.0, 3.3, 2.9,    2.6, 4.1, 3.6]) # cm
err = np.array([0.1]*10)  # 1mm

Let’s see how to use plotting routines in Matplotlib to plot these measurements with error bars to indicate the uncertainty in each measurement.

How to do it…

The following steps show how to plot measurements along with accuracy information on a figure.

First, we need to generate a new figure and axis object as usual:

fig, ax = plt.subplots()

Next, we use the errorbar method on the axis object to plot the data along with the error bars. The accuracy information (the error) is passed as the yerr argument:

ax.errorbar(measurement_id,
    measurements, yerr=err, fmt="kx", 
     capsize=2.0)

As usual, we should always add meaningful labels to the axes and a title to the plot:

ax.set_title("Plot of measurements and their estimated error")
ax.set_xlabel("Measurement ID")
ax.set_ylabel("Measurement(cm)")

Since Matplotlib will not produce xlabel ticks at every value by default, we set the x-tick values to the measurement IDs so that they are all displayed on the plot:

ax.set_xticks(measurement_id)

The resulting plot is shown in Figure 2.4. The recorded value is shown at the x markers, and the error bar extends above and below that value by an accuracy of 0.1 cm (1 mm):

Figure 2.4 - Plot of a set of 10 sample measurements (in centimeters) with their measurement error shown

Figure 2.4 - Plot of a set of 10 sample measurements (in centimeters) with their measurement error shown

We can see here that each of the markers has a vertical bar that indicates the range in which we expect the true measurement (-value) to lie.

How it works…

The errorbar method works in a similar way to other plotting methods. The first two arguments are the and coordinates of the points to be plotted. (Note that both must be provided, which is not the case for other plotting methods.) The yerr argument indicates the size of the error bars to be added to the plot and should all be positive values. The form of the value(s) passed to this argument determines the nature of the error bars. In the recipe, we provided a flat NumPy array with 10 entries—one for each measurement—which leads to error bars above and below each point with the same size (the corresponding value from the argument). Alternatively, we could have specified a 2-by-10 array, where the first row contains the lower error and the second row contains the upper error. (Since all our errors are the same, we could also have provided a single float containing the common error for all measurements.)

In addition to the data arguments, there are the usual format arguments, including the fmt format string. (We used this here as a keyword argument because we named the yerr argument that precedes it.) In addition to the formatting of lines and points found in other plotting methods, there are special arguments for customizing the look of error bars. In the recipe, we used the capsize argument to add “caps” to either end of the error bars so that we could easily identify the ends of those bars; the default style is a simple line.

There’s more...

In the recipe, we only plotted errors in the axis because the values were simply ID values. If both sets of values have uncertainty, you can also specify the error values using the xerr argument. This argument functions in the same way as the yerr argument used previously.

If you are plotting a very large number of points that follow some kind of trend, you might wish to plot error bars more selectively. For this, you can use the errorevery keyword argument to instruct Matplotlib to add error bars at every nth data point rather than at all of them. This can be either a positive integer—indicating the “stride” to use to select points that will have errors—or a tuple containing an offset from the first value and a stride. For example, errorevery=(2, 5) would place error bars every five data points, starting from the second entry.

You can also add error bars to bar charts in the same way (except here, the xerr and yerr arguments are keywords only). We could have plotted the data from the recipe as a bar chart using the following commands:

ax.bar(measurement_id, measurements, 
yerr=err, capsize=2.0, alpha=0.4)

If this line is used instead of the call to errorbar in the recipe, then we would get a bar chart, as shown in Figure 2.5:

Figure 2.5 - Bar chart of measurements with error bars

Figure 2.5 - Bar chart of measurements with error bars

As before, the measurement bar is capped with an indicator of the range in which we expect the true measurement to lie.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Compute complex mathematical problems using programming logic with the help of step-by-step recipes
  • Learn how to use Python libraries for computation, mathematical modeling, and statistics
  • Discover simple yet effective techniques for solving mathematical equations and apply them in real-world statistics

Description

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.

Who is this book for?

Whether you are a professional programmer or a student looking to solve mathematical problems computationally using Python, this is the book for you. Advanced mathematics proficiency is not a prerequisite, but basic knowledge of mathematics will help you to get the most out of this Python math book. Familiarity with the concepts of data structures in Python is assumed.

What you will learn

  • Become familiar with basic Python packages, tools, and libraries for solving mathematical problems
  • Explore real-world applications of mathematics to reduce a problem in optimization
  • Understand the core concepts of applied mathematics and their application in computer science
  • Find out how to choose the most suitable package, tool, or technique to solve a problem
  • Implement basic mathematical plotting, change plot styles, and add labels to plots using Matplotlib
  • Get to grips with probability theory with the Bayesian inference and Markov Chain Monte Carlo (MCMC) methods

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Dec 09, 2022
Length: 376 pages
Edition : 2nd
Language : English
ISBN-13 : 9781804616802
Category :
Concepts :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Dec 09, 2022
Length: 376 pages
Edition : 2nd
Language : English
ISBN-13 : 9781804616802
Category :
Concepts :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total €86.95 €96.97 €10.02 saved
Practical Discrete Mathematics
€49.99
Applying Math with Python
€37.99
Hands-On Mathematics for Deep Learning
€32.99
Total €86.95€96.97 €10.02 saved Stars icon

Table of Contents

12 Chapters
Chapter 1: An Introduction to Basic Packages, Functions, and Concepts Chevron down icon Chevron up icon
Chapter 2: Mathematical Plotting with Matplotlib Chevron down icon Chevron up icon
Chapter 3: Calculus and Differential Equations Chevron down icon Chevron up icon
Chapter 4: Working with Randomness and Probability Chevron down icon Chevron up icon
Chapter 5: Working with Trees and Networks Chevron down icon Chevron up icon
Chapter 6: Working with Data and Statistics Chevron down icon Chevron up icon
Chapter 7: Using Regression and Forecasting Chevron down icon Chevron up icon
Chapter 8: Geometric Problems Chevron down icon Chevron up icon
Chapter 9: Finding Optimal Solutions Chevron down icon Chevron up icon
Chapter 10: Improving Your Productivity Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Full star icon 5
(8 Ratings)
5 star 100%
4 star 0%
3 star 0%
2 star 0%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




Yiqiao Yin Jan 28, 2023
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I really enjoy reading this. The book reboot my knowledge in several core mathematical fields. It provides a whole package in mathematics, numpy, scipy, and matplotlib. As I progress in learning the materials, I gradually understand the topics in the book with regards to calculus, probability, and network and so on. It's a highly engineering and physics-based title. The chapters took me through a collection of miscellaneous problems with data formats and coding walkthrough. I highly recommend it!
Amazon Verified review Amazon
Akul Apr 19, 2023
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I really liked reading this title. The book helped me review my knowledge in complex as well as foundational mathematical topics with its application in Python. I’ll recommend this book for people wanting to get a refresher on mathematical concepts applicable in Machine Learning/Data Science which in turn will help improve their conceptual understanding of the model’s black box. A must read indeed!!
Amazon Verified review Amazon
H2N Nov 16, 2023
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book is an indispensable guide for Python enthusiasts tackling mathematical challenges. It begins with foundational Python packages, including NumPy and SciPy, then advances to Matplotlib for essential plotting skills. The chapters progress through calculus, differential equations, and randomness and probability basics, providing a solid mathematical base. It explores practical Python applications in areas such as trees, networks, and data analysis, and includes regression, forecasting, and geometric problem-solving. Additionally, it introduces optimization and game theory, and concludes with valuable productivity tips for Python in mathematical problem-solving, making it a comprehensive resource for varied mathematical pursuits with Python.
Amazon Verified review Amazon
Dror Feb 11, 2023
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Python has become the programming language of choice for computation in most science and engineering disciplines, including math, physics, data science and many others. This is largely due to its vast ecosystem of mathematical and scientific packages, but this large ecosystem can also be overwhelming for many students and beginners.This highly practical book provides a gentle introduction to using Python for solving problems in math and science. It begins with a clear and useful overview of the fundamental Python packages for scientific computing, such as NumPy, SciPy and Matplotlib. It then progresses to describe how to solve a diverse collection of problems in math and science using Python, in areas such as data analysis and statistics, networks, regression and forecasting, optimization, and game theory. These descriptions are clear and concise, and gradually present additional common and helpful Python packages for scientific programming.I would highly recommend this book to anyone interested in learning how to use Python for scientific computing and data analysis. It requires no more than basic knowledge of the Python programming language, and will be ideal for students in math, science and engineering who are taking their first steps in the world of scientific programming. Experienced software engineers and other Python programmers looking to expand their knowledge into scientific computing and data analysis will also highly benefit from reading this wonderful and rather unique book.
Amazon Verified review Amazon
Steven Fernandes Mar 09, 2023
Full star icon Full star icon Full star icon Full star icon Full star icon 5
The updated Applying Math with Python edition offers efficient solutions for complex problems in various mathematical fields. It includes revised old recipes and new ones to showcase tools such as JAX. You'll refresh core mathematical concepts and learn about packages in Python's scientific stack. Gradually, you'll tackle advanced topics like calculus, probability, and networks, leading to exploring Python's applications in data science, statistics, forecasting, geometry, and optimization. The book concludes with miscellaneous problems, including data formats and code acceleration. You'll gain practical coding solutions to solve various computational math and data science problems.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.