Вы находитесь на странице: 1из 25

# Week 2:

Python Libraries
and Concepts Used
in Research
PART 3: MATPLOTLIB AND PYPLOT

## Week 2 | Part 3 PH526X | USING PYTHON FOR RESEARCH 1

2.3.1:
INTRODUCTION TO MATPLOTLIB AND PYPLOT

## Week 2 | Part 3 PH526X | USING PYTHON FOR RESEARCH 2

Matplotlib and Pyplot
Matplotlib
Python plotting library that produces publication-quality figures
very large library

Pyplot
collection of functions that make matplotlib work like Matlab
provides a state machine interface to matplotlib library
process where you create figures one at a time, and all commands affect the current figure and
the current plot

## Importing Pyplot from Matplotlib

import matplotlib.pyplot as plt

## Week 2 | Part 3 PH526X | USING PYTHON FOR RESEARCH 3

plot Function
Basic plotting function (lines and markers)
plt.plot()
simplest version takes only one argument, specifying the y-axis values that
are to be plotted (like Line chart in Excel); x-axis values are the
corresponding indices, starting from 0

In [1]: plt.plot([0,1,4,9,16])
Out [1]: [<matplotlib.lines.Line2D at 0x299837efb38>]

## Week 2 | Part 3 PH526X | USING PYTHON FOR RESEARCH 4

plot Function
Add semi-colon (;) at the end of command in iPython shell
plt.plot();
suppress the printing of the plot

In [1]: plt.plot([0,1,4,9,16]);

## Week 2 | Part 3 PH526X | USING PYTHON FOR RESEARCH 5

plot Function
Two arguments:
plt.plot(x-coordinates, y-coordinates)

## In [1]: x = np.linspace(0, 10, 20)

In [2]: y = x ** 2.0
In [3]: plt.plot(x,y);

## Week 2 | Part 3 PH526X | USING PYTHON FOR RESEARCH 6

plot Function
Three arguments:
plt.plot(x, y, format string)
format string specifies the color, marker, and linestyle

Keyword arguments
supply argument by explicitly naming each parameter and specifying its
value
linewidth
markersize

## Week 2 | Part 3 PH526X | USING PYTHON FOR RESEARCH 7

Specifying color
Basic colors
b: blue
g: green
r: red
c: cyan
m: magenta
y: yellow
k: black
w: white

Gray shades can be given as a string encoding a float in the 0-1 range
color = 0.75

## Week 2 | Part 3 PH526X | USING PYTHON FOR RESEARCH 8

Specifying color
General html hex string
color = #eeefff

## General rgb or rgba tuple in the range [0,1]

color = (r, g, b) or (r, g, b, a)

## General legal html names

color = chartreuse

## Week 2 | Part 3 PH526X | USING PYTHON FOR RESEARCH 9

Specifying marker type
marker description
'-' solid line style
'--' dashed line style
'-.' dash-dot line style
':' dotted line style
'.' point marker
',' pixel marker
'o' circle marker
'v' triangle_down marker
'^' triangle_up marker
'<' triangle_left marker
'>' triangle_right marker

## Week 2 | Part 3 PH526X | USING PYTHON FOR RESEARCH 10

Specifying marker type
marker description
'1' tri_down marker
'2' tri_up marker
'3' tri_left marker
'4' tri_right marker
's' square marker
'p' pentagon marker
'*' star marker
'h' hexagon1 marker
'H' hexagon2 marker
'+' plus marker
'x' x marker

## Week 2 | Part 3 PH526X | USING PYTHON FOR RESEARCH 11

Specifying marker type
marker description
'D' diamond marker
'd' thin_diamond marker
'|' vline marker
'_' hline marker

## Week 2 | Part 3 PH526X | USING PYTHON FOR RESEARCH 12

Specifying linestyle
linestyle description
'-' or 'solid' solid line
'--' or 'dashed' dashed line
'-.' or 'dashdot' dash-dotted line
':' or 'dotted' dotted line
'None' draw nothing
' ' draw nothing

## Week 2 | Part 3 PH526X | USING PYTHON FOR RESEARCH 13

Other Keyword Arguments
(kwargs)
alpha
float (0.0 transparent through 1.0 opaque)
color or c
label
linestyle or ls
linewidth or lw
marker
markeredgecolor
markersize or ms
markevery
[None | int | length-2 tuple of int | slice | list/array of int | float | length-2
tuple of float]

2.3.2:

## Week 2 | Part 3 PH526X | USING PYTHON FOR RESEARCH 15

Other plt Functions
plt.legend(location)
provided that labels are defined in the plot function

## Adjust or get properties of axes

plt.axis([xmin, xmax, ymin, ymax])

## Set axis labes

plt.xlabel(string) and plt.ylabel(string)

Save a figure
plt.savefig(filename.file_extension)
creates filename.file_extension in the working directory

## Week 2 | Part 3 PH526X | USING PYTHON FOR RESEARCH 16

legend Function
plt.legend(location)
provided that labels are defined in the plot function
Location String Location Code
best 0
upper right 1
upper left 2
lower left 3
lower right 4
right 5
center left 6
center right 7
lower center 8
upper center 9
center 10

## Week 2 | Part 3 PH526X | USING PYTHON FOR RESEARCH 17

2.3.3:
PLOT TING USING LOGARITHMIC AXES

## Week 2 | Part 3 PH526X | USING PYTHON FOR RESEARCH 18

Logarithmic plt Functions
Creates a plot where the axes values are scaled logarithmically
by default, logarithm is taken in base 10
specify base using the keyword arguments basex/basey (scalar > 1)

plt.semilogx()
plt.semilogy()

plt.loglog()

## Week 2 | Part 3 PH526X | USING PYTHON FOR RESEARCH 19

2.3.4:
GENERATING HISTOGRAMS

## Week 2 | Part 3 PH526X | USING PYTHON FOR RESEARCH 20

hist Function
Computes and draws the histogram of an array
plt.hist(array)

plt.hist(array, bins)
(optional kwarg) bins can be an integer, or array-like, or auto
bins = np.linspace(start, end, steps)
where steps = number_of_bins + 1

plt.hist(array, normed)
(optional kwarg) normed is a bool, True or False
normalizes y-axis values

## Week 2 | Part 3 PH526X | USING PYTHON FOR RESEARCH 21

Other kwargs
plt.hist(array, cumulative)
(optional kwarg) normed is a bool, True or False
a histogram is computed where each bin gives the counts in that bin plus
all bins for smaller values. The last bin gives the total number of datapoints

plt.hist(array, histtype)
(optional kwarg) histtype is a string:
bar is a traditional bar-type histogram; multiple data are given the bars
are arranged side by side
barstacked is a bar-type histogram where multiple data are stacked on
top of each other.
step generates a lineplot that is by default unfilled.
stepfilled generates a lineplot that is by default filled.
Default is bar

## Week 2 | Part 3 PH526X | USING PYTHON FOR RESEARCH 22

subplot Function
Returns a subplot axes positioned by the given grid definition
plt.subplot(nrows, ncols, plot_number)
nrows and ncols split the figure into nrows * ncols sub-axes
plot_number identify the particular subplot that this function is to
create within the notional grid
starts at 1, increments across rows first and has a maximum of nrows * ncols
for example, if nrows = 3 and ncols = 4, the notional grid is defined as the following, with
subplot(3, 4, 10) is highlighted

1 2 3 4

5 6 7 8

9 10 11 12

## Week 2 | Part 3 PH526X | USING PYTHON FOR RESEARCH 23

subplot Function
Returns a subplot axes positioned by the given grid definition
plt.subplot(nrows, ncols, plot_number)
In the case when nrows, ncols and plot_number are all less than 10, a
3 digit number can be given instead, where
hundreds represent nrows
tens represent ncols
units represent plot_number.

subplot(211)
produces a subaxes in a figure which represents the top plot (i.e. the first)
in a 2 row by 1 column notional grid (no grid actually exists, but
conceptually this is how the returned subplot has been positioned).

## Week 2 | Part 3 PH526X | USING PYTHON FOR RESEARCH 24

Example
np.random.gamma(2, 3, 100000)
plt.figure()
plt.subplot(221)
plt.hist(x, bins=30)
plt.subplot(222)
plt.hist(x, bins=30, normed=True)
plt.subplot(223)
plt.hist(x, bins=30, cumulative=True)
plt.subplot(224)
plt.hist(x, bins=30, normed=True, cumulative=True, histtype=step)