Lec 16-19 Ch4 Matplotlib Part1
Lec 16-19 Ch4 Matplotlib Part1
Lec 16-19 Ch4 Matplotlib Part1
Disclaimer Statement
In preparation of these slides, materials have been taken from different online sources in the
shape of books, websites, research papers and presentations etc. However, the author does not
have any intention to take any benefit of these in her/his own name. This lecture (audio, video,
slides etc) is prepared and delivered only for educational purposes and is not intended to
infringe upon the copyrighted material. Sources have been acknowledged where applicable. The
views expressed are presenter’s alone and do not necessarily represent actual author(s) or the
institution.
Introduction
Matplotlib is a multiplatform data visualization library built on NumPy arrays, and designed to
work with the broader SciPy stack
IOne of Matplotlib most important features is its ability to play well with many operating
systems and graphics backbends. Matplotlib supports dozens of backbends and output types,
which means you can count on it to work regardless of which operating system you are using or
which output format you wish. This cross-platform, everything-to-everyone approach has been
one of the great strengths of Matplotlib.
General Matplotlib Tips
we will use some standard shorthand's for Matplotlib imports
Plotting from a script
If you are using Matplotlib from within a script, the function 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. So, for example, you may have a file called myplot.py containing
the following:
At this point, any plt plot command will cause a figure window to open, and further commands can
be run to update the plot. Some changes (such as modifying proper‐ ties of lines that are already
drawn) will not draw automatically; to force an update, use plt.draw(). Using plt.show() in Matplotlib
mode is not required.
(Cont..)
For this book, we will generally opt for
%matplotlib inline:
%matplotlib inline
import numpy as np
x = np.linspace(0, 10, 100)
fig = plt.figure()
plt.plot(x, np.sin(x), '-')
plt.plot(x, np.cos(x), '--');
%matplot without using inline
fig.savefig(‘filename.png’)
Or
plt.savefig(‘filename.png’)
(Cont..)
To confirm that it contains what we think it contains, let’s use the IPython Image object to
display the contents of this file
You can find the list of supported file types for your system by using the following method of the
figure canvas object:
Matplotlib & its dual interfaces
A potentially confusing feature of Matplotlib is its dual interfaces: a convenient MATLAB-style
state-based interface, and a more powerful object-oriented interface. We’ll quickly highlight the
differences between the two here.
1. MATLAB-style interface
2. Object-oriented interface
(Cont..)
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. For example, the following code will probably look quite familiar to
MATLAB users
Object-oriented interface
In the object-oriented interface the plotting functions are methods of explicit Figure and
Axes objects. To re-create the previous plot
using this style of plotting, you might do the following
%matplotlib inline
import matplotlib.pyplot as plt
plt.style.use('seaborn-whitegrid')
import numpy as np
An empty gridded axes
For all Matplotlib plots, we start by creating a figure and an axes. In their simplest
form, a figure and axes can be created as follows
Example:A simple sinusoid
we have created an axes, we can use the ax.plot function to plot some data. Let’s start with a
simple sinusoid .
fig = plt.figure()
ax = plt.axes()
x = np.linspace(0, 10, 1000)
ax.plot(x, np.sin(x));
OR
plt.plot(x, np.sin(x));
(Cont..)
we want to create a single figure with multiple lines, we can simply call the plot function
multiple times
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.
The plt.plot() function takes additional arguments that can be used to spec‐ ify these.
To adjust the color, you can use the color keyword, which accepts a string argument
representing virtually any imaginable color. The color can be specified in a variety of ways
Controlling the color of plot elements
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');
Example of various line styles
you can adjust the line style using the linestyle keyword
(Cont..)
color codes can be combined into a single non keyword argument to the plt.plot() function
Adjusting the Plot: Axes Limits
Adjusting the Plot: Axes Limits
Matplotlib does a decent job of choosing default axes limits for your plot, but some‐
times 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
Example of reversing the y-axis
If for some reason you’d like either axis to be displayed in reverse, you can simply reverse the
order of the arguments
Setting the axis limits with plt.axis
A useful related method is plt.axis() (note here the potential confusion between axes with an e,
and axis with an i).
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]
Example of a “tight” layout
The plt.axis() method goes even beyond this, allowing you to do things like automatically tighten
the bounds around the current plot
Example of an “equal” layout, with units
matched to the output resolution
It allows even higher-level specifications, such as ensuring an equal aspect ratio so that on your
screen, one unit in x is equal to one unit in y
Labeling Plots
. Examples of axis labels and title
We’ll briefly look at the labeling of plots: titles, axis labels, and simple legends.
Titles and axis labels are the simplest such labels—there are methods that can be used to
quickly set them.
(Cont..)
When multiple lines are being shown within a single axes, it can be useful to create a plot legend
that labels each line type. Again, Matplotlib has a built-in way of quickly creating such a legend.
It is done via plt.legend() method.
.
Matplotlib Gotchas
Transitioning between MATLAB and
object-oriented methods
While most plt functions translate directly to ax methods
plt.plot() → ax.plot()
plt.legend() → ax.legend()
In particular, functions to set limits, labels, and titles are slightly modified. 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()
Example of using ax.set to set multiple
properties at once
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 (
Simple Scatter Plots
Simple Scatter Plots
. Instead of points being joined by line segments, here the points are represented individually
with a dot, circle, or other shape.
line (-),
circle marker (o),
black (k)
Customizing line and point numbers
Additional keyword arguments to plt.plot specify a wide range of properties of the lines and
markers
Scatter Plots with plt.scatter
Previous method was Second method is
using plt.plot () function Using plot.Scatter() function
In scatter plots function, the properties of each individual point (size, face color, edge color, etc.) can
be individually controlled or mapped to data.
Random scatter plot using alpha
keyword
(Cont..)
For example, we might use the Iris data from Scikit-Learn, where each sample is one of three
types of flowers that has had the size of its petals and sepals carefully measured.
The Iris Dataset
This data sets consists of 3 different types of irises’ (Setosa, Versicolour, and Virginica) petal and
sepal length, stored in a 150x4 numpy.ndarray
Using point properties to encode features
of the Iris data
Visualizing Errors
Visualizing Errors
Some standard errors, confidence intervals, and likelihoods often lose their visual space in data
graphics, which leads to judgements based on simplified summaries expressed as means,
medians, etc.
In visualization of data and results, showing these errors effectively can make a plot convey
much more complete information.
For any scientific measurement, accurate accounting for errors is nearly as important
Example, the expansion rate of the universe in current literature suggests a value of around 71
― 2.5 (km/s)/Mpc, and user method has measured a value of 74 ―74 ― 5 (km/s)/Mpc
Basic Errorbars
A basic errorbar can be created with a single Matplotlib function call.
bins=5 bins=40
compute the histogram
If you would like 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:
Two-Dimensional Histograms and
Binnings
Just as we create histograms in one dimension by dividing the number line into bins.
we can also create histograms in two dimensions by dividing points among two dimensional
bins.
We’ll take a brief look at several ways to do this here. We’ll start by defining some data—an x
and y array drawn from a multivariate Gaussian distribution:
Two-dimensional histogram(plt.hist2d)
One straightforward way to plot a two-dimensional histogram is to use Matplotlib’s plt.hist2d
function
A two-dimensional histogram with
plt.hexbin
Another natural shape for such a tessellation is the regular hexagon. For this purpose, Matplotlib
provides the plt.hexbin routine, which represents a two-dimensional dataset binned within a
grid of hexagons
Customizing Plot Legends 2
Default plot legend A two-column plot legend A fancy box plot legend