Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Scientific Computing with Python - Second Edition

You're reading from  Scientific Computing with Python - Second Edition

Product type Book
Published in Jul 2021
Publisher Packt
ISBN-13 9781838822323
Pages 392 pages
Edition 2nd Edition
Languages
Authors (3):
Claus Führer Claus Führer
Profile icon Claus Führer
Jan Erik Solem Jan Erik Solem
Olivier Verdier Olivier Verdier
View More author details

Table of Contents (23) Chapters

Preface Getting Started Variables and Basic Types Container Types Linear Algebra - Arrays Advanced Array Concepts Plotting Functions Classes Iterating Series and Dataframes - Working with Pandas Communication by a Graphical User Interface Error and Exception Handling Namespaces, Scopes, and Modules Input and Output Testing Symbolic Computations - SymPy Interacting with the Operating System Python for Parallel Computing Comprehensive Examples About Packt Other Books You May Enjoy References
Plotting

Plotting in Python can be done with the pyplot part of the module Matplotlib. With matplotlibyou can create high-quality figures and graphics and also plot and visualize your results. Matplotlib is open source and freely available software. The Matplotlib website also contains excellent documentation with examples, see 35. In this section, we will show you how to use the most common features. The examples in the upcoming sections assume that you have imported the module as:

from matplotlib.pyplot import *

In case you want to use the plotting commands in IPython, it is recommended that you run the magic command %matplotlib directly after starting the IPython shell. This prepares IPython for interactive plotting.

6.1 Making plots with basic plotting commands

In this section, we will create plots by means of basic commands. It is the entry point for studying how to make graphical representations of mathematical objects and data using Python.

6.1.1 Using the plot command and some of its variants

The standard plotting function is plot. Calling plot(x,y) creates a figure window with a plot of  as a function of . The input arguments are arrays (or lists) of equal length. It is also possible to use plot(y), in which case the values in  will be plotted against their index, that is, plot(y) is a short form of plot(range(len(y)),y).

Here is an example that shows how to plot  using 200 sample points and with markers at every fourth point:

# plot sin(x) for some interval
x = linspace(-2*pi,2*pi,200)
plot(x,sin(x))

# plot marker for every 4th point
samples = x[::4]
plot(samples,sin(samples),'r*')

# add title and grid lines
title('Function sin(x) and some points plotted')
grid()

The result is shown in the following figure (Figure 6.1):

Figure 6.1: A plot of the function sin(x) with grid lines shown

As you can see, the standard plot is a solid blue...

6.1.2 Formatting

The appearance of figures and plots can be styled and customized to look how you want them to look. Some important variables are linewidth, which controls the thickness of plot lines, xlabel and ylabel, which set the axis labels, color for plot colors, and transparent for transparency.

This section will tell you how to use some of them. The following is an example with more keywords:

k = 0.2
x = [sin(2*n*k) for n in range(20)]
plot(x, color='green', linestyle='dashed', marker='o', 
                       markerfacecolor='blue', markersize=12, linewidth=6)

There are short commands that can be used if you only need basic style changes, for example, setting the color and line style. The following table (Table 6.1) shows some examples of these formatting commands. You may use either the short string syntax plot(...,'ro-'), or the more explicit syntax plot(.....

6.1.3 Working with meshgrid and contours

A common task is a graphical representation of a scalar function over a rectangle:

For this, first we have to generate a grid on the rectangle . This is done using the command meshgrid :

n = ... # number of discretization points along the x-axis
m = ... # number of discretization points along the x-axis
X,Y = meshgrid(linspace(a,b,n), linspace(c,d,m))

X and Y are arrays with an (n,m) shape such that X[i,j] and Y[i,j] contain the coordinates of the grid point , as shown in Figure 6.6:

Figure 6.6: A rectangle discretized by meshgrid.

A rectangle discretized by meshgrid will be used in the next section to visualize the behavior of an iteration, while we will use it here to plot the level curves of a function. This is done by the command contour.

 

As an example, we choose Rosenbrock's banana function:

It is used to challenge optimization methods, see [27]. The&...

6.1.4 Generating images and contours

Let's take a look at some examples of visualizing arrays as images. The following function will create a matrix of color values for the Mandelbrot fractal, see also [20]. Here, we consider a fixed-point iteration, which depends on a complex parameter, :

Depending on the choice of this parameter, it may or may not create a bounded sequence of complex values, .

For every value of , we check whether  exceeds a prescribed bound. If it remains below the bound within maxit iterations, we assume the sequence to be bounded.

Note how, in the following piece of code,meshgrid is used to generate a matrix of complex parameter values, :

def mandelbrot(h,w, maxit=20):
    X,Y = meshgrid(linspace(-2, 0.8, w), linspace(-1.4, 1.4, h))
    c = X + Y*1j
    z = c
    exceeds = zeros(z.shape, dtype=bool)

    for iteration in range(maxit):
        z  = z**2 + c
        exceeded = abs(z) > 4
        exceeds_now...

6.2 Working with Matplotlib objects directly

Till now, we have used the pyplot module of matplotlib. This module makes it easy for us to use the most important plot commands directly. Mostly, we are interested in creating a figure and displaying it immediately. Sometimes, though, we want to generate a figure that should be modified later by changing some of its attributes. This requires us to work with graphical objects in an object-oriented way. In this section, we will present some basic steps to modify figures. For a more sophisticated object-oriented approach to plotting in Python, you have to leave pyplot and have to dive directly into matplotlib with its extensive documentation.

6.2.1 Creating axes objects

When creating a plot that should be modified later, we need references to a figure and an axes object. For this, we have to create a figure first and then define some axes and their location in the figure, and we should not forget to assign these objects to a variable:

fig = figure()
ax = subplot(111)

A figure can have several axes objects depending on the use of subplot. In a second step, plots are associated with a given axes object:

fig = figure(1) 
ax = subplot(111)
x = linspace(0,2*pi,100) # We set up a function that modulates the
# amplitude of the sin function
amod_sin = lambda x: (1.-0.1*sin(25*x))*sin(x)
# and plot both...
ax.plot(x,sin(x),label = 'sin')
ax.plot(x, amod_sin(x), label = 'modsin')

Here, we used an anonymous function indicated by the keyword lambda. We will explain this construct later in Section 7.7, Anonymous functions. In fact, these two plot commands fill the list...

6.2.2 Modifying line properties

We just identified a particular line object by its label. It is an element of the list ax.lines with the index il. All of its properties are collected in a dictionary:

dict_keys(['marker', 'markeredgewidth', 'data', 'clip_box', 'solid_capstyle', 'clip_on', 'rasterized', 'dash_capstyle', 'path', 'ydata', 'markeredgecolor', 'xdata', 'label', 'alpha', 'linestyle', 'antialiased', 'snap', 'transform', 'url', 'transformed_clip_path_and_affine', 'clip_path', 'path_effects', 'animated', 'contains', 'fillstyle', 'sketch_params', 'xydata', 'drawstyle', 'markersize', 'linewidth', 'figure', 'markerfacecolor', 'pickradius...

6.2.3 Making annotations

One useful axes method is annotate. It sets an annotation at a given position and points, with an arrow, to another position in the drawing. The arrow can be given properties in a dictionary:

annot1=ax.annotate('amplitude modulated\n curve', (2.1,1.0),(3.2,0.5),
       arrowprops={'width':2,'color':'k', 
'connectionstyle':'arc3,rad=+0.5', 'shrink':0.05}, verticalalignment='bottom', horizontalalignment='left',fontsize=15, bbox={'facecolor':'gray', 'alpha':0.1, 'pad':10}) annot2=ax.annotate('corrupted data', (6.3,-0.5),(6.1,-1.1), arrowprops={'width':0.5,'color':'k','shrink':0.1}, horizontalalignment='center', fontsize=12)

In the first annotation example above, the arrow...

6.2.4 Filling areas between curves

Filling is an ideal tool for highlighting differences between curves, such as noise on top of expected data and approximations versus exact functions.

Filling is done by the axis method, fill_between:

ax.fill_between(x,y1,y2)

For the next figure, we used the following command:

axf = ax.fill_between(x, sin(x), amod_sin(x), facecolor='gray')

 

From the last chapter, we already know the NumPy method, where. In the context here, where is a very convenient parameter that requires a Boolean array to specify the additional filling conditions:

axf = ax.fill_between(x, sin(x), amod_sin(x),where=amod_sin(x)-sin(x) > 0, facecolor=’gray’)

The Boolean array that selects the regions to fill is given by the condition amod_sin(x)-sin(x) > 0.

The next figure shows the curve with both variants of filling areas:

 
Figure 6.12: The amplitude-modulated sine function with annotations and filled areas (left)...

 6.2.5 Defining ticks and tick labels

Figures in talks, posters, and publications look much nicer if they are not overloaded with unnecessary information. You want to direct the spectator to those parts that contain the message. In our example, we clean up the picture by removing ticks from the axis and the axis and by introducing problem-related tick labels:

Figure 6.13: The completed example of the amplitude-modulated sine function, with annotations and filled areas and modified ticks and tick labels

The ticks in Figure 6.13 were set by the following commands. Note the LaTeX-way of setting labels with Greek letters:

ax.set_xticks(array([0,pi/2,pi,3/2*pi,2*pi]))
ax.set_xticklabels(('$0$','$\pi/2$','$\pi$','$3/2 \pi$','$2 \pi$'),fontsize=18)
ax.set_yticks(array([-1.,0.,1]))
ax.set_yticklabels(('$-1$','$0$','$1$'),fontsize=18)

Note that we used LaTeX formatting...

6.2.6 Setting spines makes your plot more instructive – a comprehensive example

Spines are the lines with ticks and labels displaying the coordinates in a figure. If you do not take a special action, Matplotlib places them as four lines – bottom, right, top, and left, forming a frame defined by the axis parameters.

Often, pictures look better when not framed, and frequently there is a more instructive place to put the spines. In this section, we demonstrate different ways to alter the position of spines.

Let's start with a guiding example, see Figure 6.14.

Figure 6.14: A Matplotlib figure with a non-automatic placement of the spines

In this example, we choose to display only two of the four spines.

We deselected the spines at the top and on the right by using the method set_visible, and positioned the left and bottom spines in data coordinates by using the method set_position:


fig = figure(1)
ax = fig.add_axes((0.,0.,1,1))
ax.spines["left"].set_position((&apos...

6.3 Making 3D plots

There are some useful matplotlib toolkits and modules that can be used for a variety of special purposes. In this section, we describe a method for producing 3D plots.

The toolkit mplot3d provides the 3D plotting of points, lines, contours, surfaces, and all other basic components, as well as 3D rotation and scaling. A 3D plot is generated by adding the keyword projection='3d' to the axes object, as shown in the following example:

from mpl_toolkits.mplot3d import axes3d

fig = figure()
ax = fig.gca(projection='3d')
# plot points in 3D
class1 = 0.6 * random.standard_normal((200,3))
ax.plot(class1[:,0],class1[:,1],class1[:,2],'o')
class2 = 1.2 * random.standard_normal((200,3)) + array([5,4,0])
ax.plot(class2[:,0],class2[:,1],class2[:,2],'o')
class3 = 0.3 * random.standard_normal((200,3)) + array([0,3,2])
ax.plot(class3[:,0],class3[:,1],class3[:,2],'o')

As you can see,...

6.4 Making movies from plots

If you have data that evolves, you might want to save it as a movie as well as showing it in a figure window, similar to the command savefig. One way to do this is with the module visvis, see [37]

Here is a simple example of evolving a circle using an implicit representation. Let the circle be represented by the zero level, 

of a function .

Alternatively, consider the disk  inside the zero set of . If the value of decreases at a rate , then the circle will move outward at the rate .

This can be implemented as:

import visvis.vvmovie as vv

# create initial function values
x = linspace(-255,255,511)
X,Y = meshgrid(x,x)
f = sqrt(X*X+Y*Y) - 40 #radius 40

# evolve and store in a list
imlist = []
for iteration in range(200):
    imlist.append((f>0)*255)
    f -= 1 # move outwards one pixel
vv.images2swf.writeSwf('circle_evolution.swf',imlist)

The result is a flash movie (*.swf file) of a growing...

6.5 Summary

A graphical representation is the most compact form in which to present mathematical results or the behavior of an algorithm. This chapter provided you with the basic tools for plotting and introduced you to a more sophisticated way to work with graphical objects, such as figures, axes, and lines in an object-oriented way.

In this chapter, you learned how to make plots, not only classical x/y plots, but also 3D plots and histograms. We gave you an appetizer on making films. You also saw how to modify plots, considering them to be graphical objects with related methods and attributes that can be set, deleted, or modified. 

6.6 Exercises

Ex. 1: Write a function that plots an ellipse given its center coordinates (x,y), the half axis a, and b rotation angle .

Ex. 2: Write a short program that takes a 2D array, for example, the preceding Mandelbrot contour image, and iteratively replace each value by the average of its neighbors. Update a contour plot of the array in a figure window to animate the evolution of the contours. Explain the behavior.

Ex. 3: Consider an  matrix or image with integer values. The mapping

is an example of a mapping of a toroidal square grid of points onto itself. This has the interesting property that it distorts the image by shearing and then moving the pieces outside the image back using the modulo function, mod. Applied iteratively, this results in randomizing the image in a way that eventually returns the original. Implement the following sequence,

,

and save out the first steps to files or plot them in a figure...

lock icon The rest of the chapter is locked
You have been reading a chapter from
Scientific Computing with Python - Second Edition
Published in: Jul 2021 Publisher: Packt ISBN-13: 9781838822323
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.
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}