Unit - II Visualization Using Matplotlib
Unit - II Visualization Using Matplotlib
VISUALIZATION
USING
MATPLOTLIB
Importing Matplotlib – Simple line plots – Simple scatter
plots –
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. l i n s p a c e ( 0 , 10 , creates
100 ) an array o f 100
ev en l y space
d
v a l u e s from 0 t o 10 .
np. sin( x) and np. cos( x)
feul e
nmc tei onnt sin ct h
ael c array.
ulat e the sine
and c o s i n e v a l u e s o f e a c h
plot() d i s ptl a
plt. show() ion
y s itshues e d
plot. to
tt i n g
. P l o
2
r
f aomn
y t h
eol n
l ?
P
I S h
?
e n ce
i ff e r i p t
D e e n
n s c r
e
bpy twt ho
n dy t h o n
aIP ?
he ll?
S
DIFFERENC E B E T W E E N P Y T H O N
S C R I P T AND I PY T H O N SHELL
A script contains a list of commands to
execute in order.
It runs from start to finish and display some
output. On the contrary,with IPython, you
generally write one command at a
time and you get the results
instantly.
This is a completely different way of
2 . P LO TT I N G F R O M A N I PY T H O N
SHELL
IPython is built to work well
with Matplotlib if you specify
Matplotlib mode.
To enable this mode, you can use
%matplotlib command after starting ipython:
%matplotlib
import matplotlib.pyplot as plt
Plot command will cause a figure window to
open and further commands can be run to
2 . P LO TT I N G F R O M A N I PY T H O N
SHELL
Some changes or modifications will not dra
w
automatically: to force an update, use
plt.draw(). plt.show() is not required.
tt i n g
. P l o
3
r
f aomn
y t h
boon
o k
I
NP o te
?
3 . P LO TT I N G F R O M A N I PY T H O N
N O T E BO O K
IPython Notebook is a browser based
interactive data analysis tool that can
combine narrative code, graphics, HTML
elements and much more i nto a single
document.
Plotting can be done with %matplotlib
command as similar to IPython shell.
t i o n s
O p
fo r d i n g
m b e d n
e i c
cst l y i
ra p ihr e
g d b oo k
thno e t e
%matplotlib notebook - will lead
to interactive plots
% matplotlibinline
import matplotlib. pyplot
as plt
plt. style. use(' seaborn-
whitegrid')
import numpy as np
x = np.linspace(0, 10, 30)
y = np.sin(x)
plt.plot(x, y, 'o',
color='black');
. p l o t
p l t
. p l o t ?
s
vax .
?
import
matplotlib. pyplot
as plt
f i g = p l t . f i g u re ( )
i m p o r tn u m p ya s n p
x = np. l i n s p a c e ( 0 ,
10 , 1 0 0 0 )
plt. plot( x, np.
s i n ( x));
f ig = plt. f
igure() a x = p l t .
axes()
x = np. l i n s p a c e ( 0 ,
10 , 1 0 0 0 )
a x . p l o t ( x , n p . s i n ( x));
plt.ylim(1.2, -1.2);
Adjusting the Plot: Axes
Limits
plt.axis('tight');
plt.axis('tight') - adjusts
plt.plot(x, np.sin(x))
plt.title("A Sine
Curve")
plt.xlabel("x")
plt.ylabel("sin(x)");
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();
plt.legend()
Aside: Matplotlib
Gotchas
“Matplotlib Gotchas" refer to common issues or
pitfalls that users might encounter when working with
Matplotlib. 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()
ax = plt.axes()
ax.plot(x,
np.sin(x))
ax.set(xlim=(0,
10),
ylim=(-2,
2),xlabel='x',
ylabel='sin(x)', title='A
Visualizing
Errors
• Any statistical data inevitably contains errors
• An error in statistics is simply a difference between the
measured value and the actual value
• Plotting errors on your charts is a way to convey more
information.
• A graphical representation of errors or uncertainties in the
measurement is called an error bar.
• Error bars are included in Matplotlib line plots and graphs.
Visualizing
•
Errors
It's a line (a cap line, sometimes) drawn from the data
point.
• The line's length shows us how precise the
measurement is.
• A short error bar means that the values are
concentrated, and the data is reliable.
• A long error bar indicates that the values are spread
out, and the data is likely to contain errors.
• In visualization, showing these errors effectively can
make a plot convey much more complete information.
Adding Error bar in
Matplotlib
plt.errorbar(x, y, yerr = 2, capsize=3)
RdGy - Red-
Gray
Matplotli has a wide range of
b colormaps which you can easily
available browsein
IPython by doing a tab completion on the
,plt.cm module:
plt.cm.<TAB>
The spaces between the lines may be a
bit distracting.
We can change this by switchingto a
filled contour plot using the plt.contourf()
function
plt.contourf(X, Y, Z,
plt.colorbar 20, cmap='RdGy')
plt.colorbar();
() whic
command, h
automatical
creates an
ly
additional axis
with labeled
color information
for the plot.
t o g r a
H i s
, i n g s
Bmi n n ?
d n s i t y
aDn e
?
HISTOGRAMS,
BINNINGS
%matplotlib inline & DENSITY
import numpy as
np
import
matplotlib.pyplot as plt
plt.style.use('seaborn-
white')
data =
In the context of a histogram, "bins"
refer to the intervals into which the
data range is divided.
If you have a dataset of exam scores
ranging from 0 to 100, and you
choose 10 bins, the histogram will
group the scores into 10 intervals,
such as 0-10, 11-20, 21-30, and so on
HISTOGRAMS,
BINNINGS
& DENSITY
plt.hist(data, bins=30,
normed=True,alpha=0.5,
his
ttype='stepfilled',color=
'ste
TWO
DIMENSIONAL
HISTOGRAMS AND
We create histograms in one
BINNINGS
dimension by dividing the number-line
into bins, we can also create histograms
in two-dimensions by dividing points
among two-dimensional bins.
To plot a two-dimensional histogram is to
plt.hist2d(x, y,
bins=30,
cmap='Blues')
cb = plt.colorbar()
cb.set_label('counts
in bin')
1.Map Projections
2.Cylindrical projections
3.Pseudo-cylindrical
projections
4.Perspective projections
5.Conic projections
DRAWIN G A M A P
B A C K G R O U N D
Physical boundaries and bodies of water
1. drawcoastlines(): Draw continental coast
lines 2. drawlsmask(): Draw a mask
between the land andsea, for use with
projecting images on
one or the other
3.drawmapboundary(): Drawthe
map boundary, including
the fill color for oceans.
4.drawrivers(): Draw rivers on the map
5.fillcontinents(): Fill the continents with a
given color; optionally fill lakes