Talk Matplotlib PDF
Talk Matplotlib PDF
BIOSIGNAL MANIPULATION
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.
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.
MATPLOTLIB
GENERAL MATPLOTLIB TIPS
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:
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.
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.
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
GENERAL MATPLOTLIB TIPS
Saving Figures to File
• One nice feature of Matplotlib is the ability to save figures in a
wide variety of formats.
fig.savefig('my_figure.png')
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.
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.
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.
MATPLOTLIB
OBJECT-ORIENTED INTERFACE
• To re-create the previous plot using this style of plotting, you
might do the following:
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));
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.
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:
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.
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');
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.
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:
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
MATPLOTLIB
HISTOGRAMS, BINNINGS, AND DENSITY
• The combination of histtype='stepfilled' along with some
transparency alpha is very useful when comparing histograms
of several distributions:
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:
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
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.
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.
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).
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.
MATPLOTLIB
MULTIPLE SUBPLOTS
plt.subplot: Simple Grids of Subplots
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.
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:
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.
MATPLOTLIB
MULTIPLE SUBPLOTS
plt.subplots: The Whole Grid in One Go