0% found this document useful (0 votes)
15 views

Talk Matplotlib PDF

This document discusses the Matplotlib library, a Python data visualization library used for plotting and visualizing data. It provides an overview of Matplotlib, general tips for using it, and examples of simple line plots. Matplotlib can be used for plotting data either from scripts or interactively from the IPython shell or notebook. It supports both MATLAB-style and object-oriented interfaces.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Talk Matplotlib PDF

This document discusses the Matplotlib library, a Python data visualization library used for plotting and visualizing data. It provides an overview of Matplotlib, general tips for using it, and examples of simple line plots. Matplotlib can be used for plotting data either from scripts or interactively from the IPython shell or notebook. It supports both MATLAB-style and object-oriented interfaces.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 54

BASIC SCIENTIFIC LIBRARIES FOR

BIOSIGNAL MANIPULATION

John Fredy Ochoa Gómez


Bioengineering Department
University of Antioquia
Basic Scientific libraries for biosignal manipulation 2

MATPLOTLIB
Basic Scientific libraries for biosignal manipulation 3

MATPLOTLIB
INTRODUCTION
• Matplotlib is a multiplatform data visualization library built on
NumPy arrays, and designed to work with the broader SciPy
stack.

• It was conceived originally as a patch to IPython for enabling


interactive MATLAB-style plotting via gnuplot from the IPython
command line.
Basic Scientific libraries for biosignal manipulation 4

MATPLOTLIB
INTRODUCTION
• It received an early boost when it was adopted as the plotting
package of choice of the Space Telescope Science Institute
(the folks behind the Hubble Telescope), which financially
supported Matplotlib’s development and greatly expanded its
capabilities.
Basic Scientific libraries for biosignal manipulation 5

MATPLOTLIB
INTRODUCTION
• Newer tools like ggplot and ggvis in the R language, along
with web visualization toolkits based on D3js and HTML5
canvas, often make Matplotlib feel old-fashioned.

• Recent Matplotlib versions make it relatively easy to set new


global plotting styles
Basic Scientific libraries for biosignal manipulation 6

MATPLOTLIB
GENERAL MATPLOTLIB TIPS

• Importing matplotlib just as we use the np shorthand for


NumPy we will use some standard shorthands for Matplotlib
imports:

import matplotlib as mpl


import matplotlib.pyplot as plt
Basic Scientific libraries for biosignal manipulation 7

MATPLOTLIB
GENERAL MATPLOTLIB TIPS
Plotting from a script
• If you are using Matplotlib from within a script, the function
plt.show() is your friend.
• plt.show() starts an event loop, looks for all currently active figure
objects, and opens one or more interactive windows that display your
figure or figures.

• Example:

import matplotlib.pyplot as plt


import numpy as np
x = np.linspace(0, 10, 100)
plt.plot(x, np.sin(x))
plt.plot(x, np.cos(x))
plt.show()
Basic Scientific libraries for biosignal manipulation 8

MATPLOTLIB
GENERAL MATPLOTLIB TIPS
Plotting from a script
• One thing to be aware of: the plt.show() command should be
used only once per Python session, and is most often seen at
the very end of the script.

• Multipleshow() commands can lead to unpredictable


backend-dependent behavior, and should mostly be avoided.
Basic Scientific libraries for biosignal manipulation 9

MATPLOTLIB
GENERAL MATPLOTLIB TIPS
Plotting from an IPython shell
• It can be very convenient to use Matplotlib interactively within
an IPython shell.
• IPython is built to work well with Matplotlib if you specify
Matplotlib mode:

%matplotlib
import matplotlib.pyplot as plt

• At this point, any plt plot command will cause a figure window
to open, and further commands can be run to update the plot
Basic Scientific libraries for biosignal manipulation 10

MATPLOTLIB
GENERAL MATPLOTLIB TIPS
Plotting from an IPython notebook
• The IPython notebook is a browser-based interactive data
analysis tool that can combine narrative, code, graphics,
HTML elements, and much more into a single executable
document.

• Plotting interactively within an IPython notebook can be done


with the %matplotlib command, and works in a similar way to
the IPython shell.
Basic Scientific libraries for biosignal manipulation 11

MATPLOTLIB
GENERAL MATPLOTLIB TIPS
Plotting from an IPython notebook
• In the IPython notebook, you also have the option of
embedding graphics directly in the notebook, with two
possible options:

%matplotlib notebook #interactive plots embedded within the notebook


%matplotlib inline #static images embedded in the notebook
Basic Scientific libraries for biosignal manipulation 12

MATPLOTLIB
GENERAL MATPLOTLIB TIPS
Saving Figures to File
• One nice feature of Matplotlib is the ability to save figures in a
wide variety of formats.

• You can save a figure using the savefig() command.

fig.savefig('my_figure.png')

• In savefig(), the file format is inferred from the extension of the


given filename.
Basic Scientific libraries for biosignal manipulation 13

MATPLOTLIB
GENERAL MATPLOTLIB TIPS
• Depending on what backends you have installed, many
different file formats are available.

• The list of supported file types for the system can be obtained
by using the following method of the figure canvas object:

fig.canvas.get_supported_filetypes()
{'eps': 'Encapsulated Postscript',
'jpeg': 'Joint Photographic Experts Group',
'jpg': 'Joint Photographic Experts Group',
'pdf': 'Portable Document Format', …
Basic Scientific libraries for biosignal manipulation 14

MATPLOTLIB
MATLAB-STYLE INTERFACE
• Matplotlib was originally written as a Python alternative for
MATLAB users, and much of its syntax reflects that fact.

• The MATLAB-style tools are contained in the pyplot (plt)


interface.

• The following code is similar to MATLAB:


plt.figure() # create a plot figure
# create the first of two panels and set current axis
plt.subplot(2, 1, 1) # (rows, columns, panel number)
plt.plot(x, np.sin(x))
# create the second panel and set current axis
plt.subplot(2, 1, 2)
plt.plot(x, np.cos(x));
Basic Scientific libraries for biosignal manipulation 15

MATPLOTLIB
MATLAB-STYLE INTERFACE
• It’s important to note that this interface is stateful: it keeps
track of the “current” figure and axes, which are where all plt
commands are applied.

• While this stateful interface is fast and convenient for simple


plots, it is easy to run into problems.
• For example, once the second panel is created, how can we go back
and add something to the first?
Basic Scientific libraries for biosignal manipulation 16

MATPLOTLIB
OBJECT-ORIENTED INTERFACE
• The object-oriented interface is available for these more
complicated situations, and for when you want more control
over your figure.

• Rather than depending on some notion of an “active” figure or


axes, in the object-oriented interface the plotting functions are
methods of explicit Figure and Axes objects.
Basic Scientific libraries for biosignal manipulation 17

MATPLOTLIB
OBJECT-ORIENTED INTERFACE
• To re-create the previous plot using this style of plotting, you
might do the following:

# First create a grid of plots


# ax will be an array of two Axes objects
fig, ax = plt.subplots(2)
# Call plot() method on the appropriate object
ax[0].plot(x, np.sin(x))
ax[1].plot(x, np.cos(x));
Basic Scientific libraries for biosignal manipulation 18

MATPLOTLIB
SIMPLE LINE PLOTS
• Perhaps the simplest of all plots is the visualization of a single
function y = f(x).

%matplotlib inline
import matplotlib.pyplot as plt
plt.style.use('seaborn-whitegrid')
import numpy as np
fig = plt.figure()
ax = plt.axes()
x = np.linspace(0, 10, 1000)
ax.plot(x, np.sin(x));

• Alternatively, using pylab interface


plt.plot(x, np.sin(x));
Basic Scientific libraries for biosignal manipulation 19

MATPLOTLIB
SIMPLE LINE PLOTS
• The figure (an instance of the class plt.Figure) can be thought
of as a single container that contains all the objects
representing axes, graphics, text, and labels.

• The axes (an instance of the class plt.Axes) is what we see


above: a bounding box with ticks and labels, which will
eventually contain the plot elements that make up our
visualization.
Basic Scientific libraries for biosignal manipulation 20

MATPLOTLIB
SIMPLE LINE PLOTS
• If we want to create a single figure with multiple lines, we can
simply call the plot function multiple times:

plt.plot(x, np.sin(x))
plt.plot(x, np.cos(x));
Basic Scientific libraries for biosignal manipulation 21

MATPLOTLIB
SIMPLE LINE PLOTS
Adjusting the plot: line colors and styles
• The first adjustment you might wish to make to a plot is to
control the line colors and styles.

• To adjust the color, you can use the color keyword, which
accepts a string argument representing virtually any
imaginable color.
Basic Scientific libraries for biosignal manipulation 22

MATPLOTLIB
SIMPLE LINE PLOTS
Adjusting the plot: line colors and styles
• The color can be specified in a variety of ways:

plt.plot(x, np.sin(x - 0), color='blue') # specify color by name


plt.plot(x, np.sin(x - 1), color='g') # short color code (rgbcmyk)
plt.plot(x, np.sin(x - 2), color='0.75') # Grayscale between 0 and 1
plt.plot(x, np.sin(x - 3), color='#FFDD44') # Hex code (RRGGBB from 00 to FF)
plt.plot(x, np.sin(x - 4), color=(1.0,0.2,0.3)) # RGB tuple, values 0 and 1
plt.plot(x, np.sin(x - 5), color='chartreuse'); # all HTML color names supported
Basic Scientific libraries for biosignal manipulation 23

MATPLOTLIB
SIMPLE LINE PLOTS
Adjusting the plot: line colors and styles
• If no color is specified, Matplotlib will automatically cycle
through a set of default colors for multiple lines.
• You can adjust the line style using the linestyle keyword:

plt.plot(x, x + 0, linestyle='solid')
plt.plot(x, x + 1, linestyle='dashed')
plt.plot(x, x + 2, linestyle='dashdot')
plt.plot(x, x + 3, linestyle='dotted');
# For short, you can use the following codes:
plt.plot(x, x + 4, linestyle='-') # solid
plt.plot(x, x + 5, linestyle='--') # dashed
plt.plot(x, x + 6, linestyle='-.') # dashdot
plt.plot(x, x + 7, linestyle=':'); # dotted
Basic Scientific libraries for biosignal manipulation 24

MATPLOTLIB
SIMPLE LINE PLOTS
Adjusting the plot: Axes Limits
• Matplotlib does a decent job of choosing default axes limits for
your plot, but sometimes it’s nice to have finer control.

• The most basic way to adjust axis limits is to use the plt.xlim()
and plt.ylim() methods:

plt.plot(x, np.sin(x))
plt.xlim(-1, 11)
plt.ylim(-1.5, 1.5);
Basic Scientific libraries for biosignal manipulation 25

MATPLOTLIB
SIMPLE LINE PLOTS
Adjusting the plot: Axes Limits
• If for some reason you’d like either axis to be displayed in
reverse, you can simply reverse the order of the arguments:

plt.plot(x, np.sin(x))
plt.xlim(10, 0)
plt.ylim(1.2, -1.2);
Basic Scientific libraries for biosignal manipulation 26

MATPLOTLIB
SIMPLE LINE PLOTS
Adjusting the plot: Axes Limits
• The plt.axis() method allows you to set the x and y limits with
a single call, by passing a list that specifies [xmin, xmax,
ymin, ymax] :

plt.plot(x, np.sin(x))
plt.axis([-1, 11, -1.5, 1.5]);
Basic Scientific libraries for biosignal manipulation 27

MATPLOTLIB
SIMPLE LINE PLOTS
Adjusting the plot: Axes Limits
• The plt.axis() method goes even beyond this, allowing you to
do things like automatically tighten the bounds around the
current plot:

plt.plot(x, np.sin(x))
plt.axis('tight');

plt.plot(x, np.sin(x))
plt.axis('equal');
Basic Scientific libraries for biosignal manipulation 28

MATPLOTLIB
LABELING PLOTS
• Titles and axis labels are the simplest such labels. There are
methods that can be used to quickly set them:

plt.plot(x, np.sin(x))
plt.title("A Sine Curve")
plt.xlabel("x")
plt.ylabel("sin(x)");
Basic Scientific libraries for biosignal manipulation 29

MATPLOTLIB
LABELING PLOTS
• When multiple lines are being shown within a single axes, it
can be useful to create a plot legend that labels each line
type.

plt.plot(x, np.sin(x), '-g', label='sin(x)')


plt.plot(x, np.cos(x), ':b', label='cos(x)')
plt.axis('equal')
plt.legend();
Basic Scientific libraries for biosignal manipulation 30

MATPLOTLIB
MATPLOTLIB GOTCHAS
• While most plt functions translate directly to ax methods (such
as plt.plot() → ax.plot(), plt.legend() → ax.legend(), etc.), this
is not the case for all commands.
• In particular, functions to set limits, labels, and titles are slightly
modified.
• For transitioning between MATLAB-style functions and object-
oriented methods, make the following changes:
plt.xlabel() → ax.set_xlabel()
plt.ylabel() → ax.set_ylabel()
plt.xlim() → ax.set_xlim()
plt.ylim() → ax.set_ylim()
plt.title() → ax.set_title()
Basic Scientific libraries for biosignal manipulation 31

MATPLOTLIB
MATPLOTLIB GOTCHAS
• In the object-oriented interface to plotting, rather than calling
these functions individually, it is often more convenient to use
the ax.set() method to set all these properties at once:

ax = plt.axes()
ax.plot(x, np.sin(x))
ax.set(xlim=(0, 10), ylim=(-2, 2), xlabel='x', ylabel='sin(x)',
title='A Simple Plot');
Basic Scientific libraries for biosignal manipulation 32

MATPLOTLIB
SIMPLE SCATTER PLOTS
• Here the points are represented individually with a dot, circle,
or other shape.

plt.scatter(x, y, marker='o');

• The primary difference of plt.scatter from plt.plot is that it can


be used to create scatter plots where the properties of each
individual point (size, face color, edge color, etc.) can be
individually controlled or mapped to data.

• For large datasets plt.plot should be preferred over plt.scatter.


Basic Scientific libraries for biosignal manipulation 33

MATPLOTLIB
SIMPLE SCATTER PLOTS

rng = np.random.RandomState(0)
x = rng.randn(100)
y = rng.randn(100)
colors = rng.rand(100)
sizes = 1000 * rng.rand(100)
plt.scatter(x, y, c=colors, s=sizes, alpha=0.3, cmap='viridis')
plt.colorbar();
• Notice that the color argument is automatically
mapped to a color scale (shown here by the
colorbar() command), and the size argument is
given in pixels.

• In this way, the color and size of points can be


used to convey information in the visualization,
in order to illustrate multidimensional data.
Basic Scientific libraries for biosignal manipulation 34

MATPLOTLIB
BASIC ERRORBARS
• A basic errorbar can be created with a single Matplotlib
function call:

%matplotlib
import matplotlib.pyplot as plt
plt.style.use('seaborn-whitegrid')
import numpy as np
x = np.linspace(0, 10, 50)
dy = 0.8
y = np.sin(x) + dy * np.random.randn(50)
plt.errorbar(x, y, yerr=dy, fmt='.k');
Basic Scientific libraries for biosignal manipulation 35

MATPLOTLIB
BASIC ERRORBARS
• I often find it helpful, especially in crowded plots, to make the
errorbars lighter than the points themselves:

plt.errorbar(x, y, yerr=dy, fmt='o', color='black', ecolor='lightgray',


elinewidth=3, capsize=0);

• In addition to these options, you can also specify horizontal


errorbars (xerr), onesided errorbars, and many other variants.

• For more information on the options available, refer to the


docstring of plt.errorbar.
Basic Scientific libraries for biosignal manipulation 36

MATPLOTLIB
HISTOGRAMS, BINNINGS, AND DENSITY
• A simple histogram can be a great first step in understanding
a dataset.

import numpy as np
import matplotlib.pyplot as plt
plt.style.use('seaborn-white')
data = np.random.randn(1000)
plt.hist(data);
Basic Scientific libraries for biosignal manipulation 37

MATPLOTLIB
HISTOGRAMS, BINNINGS, AND DENSITY
• The hist() function has many options to tune both the
calculation and the display

plt.hist(data, bins=30, normed=True, alpha=0.5, histtype='stepfilled',


color='steelblue', edgecolor='none');
Basic Scientific libraries for biosignal manipulation 38

MATPLOTLIB
HISTOGRAMS, BINNINGS, AND DENSITY
• The combination of histtype='stepfilled' along with some
transparency alpha is very useful when comparing histograms
of several distributions:

x1 = np.random.normal(0, 0.8, 1000)


x2 = np.random.normal(-2, 1, 1000)
x3 = np.random.normal(3, 2, 1000)
kwargs = dict(histtype='stepfilled', alpha=0.3, normed=True, bins=40)
plt.hist(x1, **kwargs)
plt.hist(x2, **kwargs)
plt.hist(x3, **kwargs);
Basic Scientific libraries for biosignal manipulation 39

MATPLOTLIB
HISTOGRAMS, BINNINGS, AND DENSITY
• To simply compute the histogram (that is, count the number of
points in a given bin) and not display it, the np.histogram()
function is available:

counts, bin_edges = np.histogram(data, bins=5)


Basic Scientific libraries for biosignal manipulation 40

MATPLOTLIB
HISTOGRAMS, BINNINGS, AND DENSITY
Two-Dimensional Histograms and Binnings

mean = [0, 0]
cov = [[1, 1], [1, 2]]
x, y = np.random.multivariate_normal(mean, cov, 10000).T
plt.hist2d(x, y, bins=30, cmap='Blues')
cb = plt.colorbar()
cb.set_label('counts in bin')
Basic Scientific libraries for biosignal manipulation 41

MATPLOTLIB
HISTOGRAMS, BINNINGS, AND DENSITY
Two-Dimensional Histograms and Binnings

• plt.hist2d has a counterpart in np.histogram2d, which can be


used as follows:

counts, xedges, yedges = np.histogram2d(x, y, bins=30)


Basic Scientific libraries for biosignal manipulation 42

MATPLOTLIB
MULTIPLE SUBPLOTS
• Sometimes it is helpful to compare different views of data side
by side. To this end, Matplotlib has the concept of subplots:
groups of smaller axes that can exist together within a single
figure.

• These subplots might be insets, grids of plots, or other more


complicated layouts. In this section, we’ll explore four routines
for creating subplots in Matplotlib.
Basic Scientific libraries for biosignal manipulation 43

MATPLOTLIB
MULTIPLE SUBPLOTS
plt.axes: Subplots by Hand
• The most basic method of creating an axes is to use the
plt.axes function. As we’ve seen previously, by default this
creates a standard axes object that fills the entire figure.

• plt.axes also takes an optional argument that is a list of four


numbers in the figure coordinate system. These numbers
represent [bottom, left, width, height] in the figure coordinate
system, which ranges from 0 at the bottom left of the figure to
1 at the top right of the figure.
Basic Scientific libraries for biosignal manipulation 44

MATPLOTLIB
MULTIPLE SUBPLOTS
plt.axes: Subplots by Hand
• For example, we might create an inset axes at the top-right
corner of another axes by setting the x and y position to 0.65
(that is, starting at 65% of the width and 65% of the height of
the figure) and the x and y extents to 0.2 (that is, the size of
the axes is 20% of the width and 20% of the height of the
figure).

import matplotlib.pyplot as plt


plt.style.use('seaborn-white')
import numpy as np
ax1 = plt.axes() # standard axes
ax2 = plt.axes([0.65, 0.65, 0.2, 0.2])
Basic Scientific libraries for biosignal manipulation 45

MATPLOTLIB
MULTIPLE SUBPLOTS
plt.axes: Subplots by Hand
• The equivalent of this command within the object-oriented
interface is fig.add_axes(). Let’s use this to create two
vertically stacked axes:

fig = plt.figure()
ax1 = fig.add_axes([0.1, 0.5, 0.8, 0.4],
xticklabels=[], ylim=(-1.2, 1.2))
ax2 = fig.add_axes([0.1, 0.1, 0.8, 0.4],
ylim=(-1.2, 1.2))
x = np.linspace(0, 10)
ax1.plot(np.sin(x))
ax2.plot(np.cos(x));
Basic Scientific libraries for biosignal manipulation 46

MATPLOTLIB
MULTIPLE SUBPLOTS
plt.subplot: Simple Grids of Subplots
• Aligned columns or rows of subplots are a common enough
need that Matplotlib has several convenience routines that
make them easy to create.

• The lowest level of these is plt.subplot(), which creates a


single subplot within a grid.

• This command takes three integer arguments—the number of


rows, the number of columns, and the index of the plot to be
created in this scheme, which runs from the upper left to the
bottom right
Basic Scientific libraries for biosignal manipulation 47

MATPLOTLIB
MULTIPLE SUBPLOTS
plt.subplot: Simple Grids of Subplots

for i in range(1, 7):


plt.subplot(2, 3, i)
plt.text(0.5, 0.5, str((2, 3, i)),fontsize=18, ha='center')
Basic Scientific libraries for biosignal manipulation 48

MATPLOTLIB
MULTIPLE SUBPLOTS
plt.subplot: Simple Grids of Subplots
• The command plt.subplots_adjust can be used to adjust the
spacing between these plots.

fig = plt.figure()
fig.subplots_adjust(hspace=0.4, wspace=0.4)
for i in range(1, 7):
ax = fig.add_subplot(2, 3, i)
ax.text(0.5, 0.5, str((2, 3, i)), fontsize=18, ha='center')
Basic Scientific libraries for biosignal manipulation 49

MATPLOTLIB
MULTIPLE SUBPLOTS
plt.subplot: Simple Grids of Subplots
Basic Scientific libraries for biosignal manipulation 50

MATPLOTLIB
MULTIPLE SUBPLOTS
plt.subplots: The Whole Grid in One Go
• The approach just described can become quite tedious when
you’re creating a large grid of subplots, especially if you’d like
to hide the x- and y-axis labels on the inner plots.

• For this purpose, plt.subplots() is the easier tool to use (note


the s at the end of subplots).

• Rather than creating a single subplot, this function creates a


full grid of subplots in a single line, returning them in a NumPy
array.
Basic Scientific libraries for biosignal manipulation 51

MATPLOTLIB
MULTIPLE SUBPLOTS
plt.subplots: The Whole Grid in One Go
• The arguments are the number of rows and number of
columns, along with optional keywords sharex and sharey,
which allow you to specify the relationships between different
axes.

• Here we’ll create a 2×3 grid of subplots, where all axes in the
same row share their y-axis scale, and all axes in the same
column share their x-axis scale:

fig, ax = plt.subplots(2, 3, sharex='col', sharey='row')


Basic Scientific libraries for biosignal manipulation 52

MATPLOTLIB
MULTIPLE SUBPLOTS
plt.subplots: The Whole Grid in One Go
Basic Scientific libraries for biosignal manipulation 53

MATPLOTLIB
MULTIPLE SUBPLOTS
plt.subplots: The Whole Grid in One Go
• Note that by specifying sharex and sharey, we’ve
automatically removed inner labels on the grid to make the
plot cleaner.

• The resulting grid of axes instances is returned within a


NumPy array, allowing for convenient specification of the
desired axes using standard array indexing notation
# axes are in a two-dimensional array, indexed by [row, col]
for i in range(2):
for j in range(3):
ax[i, j].text(0.5, 0.5, str((i, j)), fontsize=18, ha='center')
fig
Basic Scientific libraries for biosignal manipulation 54

MATPLOTLIB
MULTIPLE SUBPLOTS
plt.subplots: The Whole Grid in One Go

You might also like