KEMBAR78
Unit 5 | PDF | Scatter Plot | Visualization (Graphics)
0% found this document useful (0 votes)
19 views25 pages

Unit 5

The document outlines a syllabus for a course on data visualization using Matplotlib and Seaborn, covering topics such as importing libraries, creating various types of plots, and customizing visualizations. It includes sections on line plots, scatter plots, histograms, and geographic data visualization, as well as practical examples and code snippets. Additionally, it discusses saving plots to disk and setting axis properties for better presentation of data.

Uploaded by

laya rose
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views25 pages

Unit 5

The document outlines a syllabus for a course on data visualization using Matplotlib and Seaborn, covering topics such as importing libraries, creating various types of plots, and customizing visualizations. It includes sections on line plots, scatter plots, histograms, and geographic data visualization, as well as practical examples and code snippets. Additionally, it discusses saving plots to disk and setting axis properties for better presentation of data.

Uploaded by

laya rose
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

UNITV

~ata Visualization

--Syllabus _____
I______

Importing Matplotlib - Line plots - Scatter plots - visualizing errors - density and contour
plots - Histograms - legends - colors - subplots - text and annotation - customization -
three dimensional plotting - Geographic Data with Basemap - Visualization with Seaborn.

Contents
5.1 Importing Matplotlib
5.2 Scatter Plots
5.3 Visualizing Errors
5.4 Density and Contour Plots
5.5 Histogram
5.6 Legend
5.7 Subplots
5.8 Text and Annotation
5.9 Customization
5.10 Three Dimensional Plotting
5.11 Geographic Data
with Basemap
5.12
Visualization with Seaborn
5 3
·1 Two Marks Questions with Answers

(5 - 1)
011111 Vis11011
'ir,f/011

bJ 5, 1 lmpt'rtin g Matplotl ib

.....; .,"'~-'' , ':' ,!'


\ ,..-~ .-.,1,",,, :--' ·,\ ,' 1·11'1"'\I'\
,,,,n\t. '" · . 1:,1•
, ·' ·\tt'·•.
,•' l'l','\(1· ,,_,,._ ."(. , ,' \ll1· ,,,.· \ll' ll, ,' \llll . t
• J 111 cractiv~

• \ L:7:-'.,•:'.:~ ,!' .1 / ,' Hli\~ iil' t":\t ~ 1~,r th,' Pytlh,n prl,gmmm ing. l:mguag.~. It allows 10 niakc
~.. .::~>:: ;~.:~ in fr'\\ lmt'!' ,,t -.' ("fk. \ h,st ,,f thl' l,t h~r p~11hlm pll)II ing Iihrary arc hui Id 011 lop
. "'. . . . \ ~--17:': \,~!~~.
limi1;.,,i h' ~n l'lltput. hut it still prnvicks you wi th the means 10

~ 5. 1.1 Visualizi ng Informat ion : Starting with Graph

• :)~:-..1 \°":!':.:.~1_-:.1:-: ,,11 i!' th;:- rr-.:-s.:-n~1t.i,'\n l°,f qnamitativ c intlmnatio n m a graphical form. In
, :. . ___~~ ,, -.,:-...::-. .5.:n-:1 \i !'n:1li~1ti1.'ln:- mm hrgl' and small datasets into visuals tlu1t are easier for

• 0 ,,'-.: L,:3 \l !'l:~i~Hi,'\ns :1n:- 1..·n:-~m'<l when 1..·ommunication, data science, and design collide.
-:).::.:-2 \"::";:.:.tli::'..lt0r.s . .11..'n ~ right 1.-,ffc'r key insights into complicat ed datasets in ways that are

• .-\ ~.!;-:-1 ::: . !''.ff{'ly .1 \l Sual represcnmti(in of muueric data. MatPlotLib supports a large
::1..:.-...:~:- t' J° ~1-;-:1 ..md ..·h:m rypes.
10
• .\ ~2:;~..,:Jit" is .! f'' rul..lr ~1111..,n p:1ck.;,1ge used ro build plots. Matplotlib can also be used
~ "-.:- : D ~:1.,1s ..md mirrurions .
• i.. !=:;- ? :<-'IS ..-ml t""c.' Cre3te-d in ~111\""'lll ,,ith Marplotlib's pyplot library. To build a line plot,
:::-s: ::-::.:,"'.: .\ brpl(xlib. lt is :.1 :-t:3..11d:.1rd cunYent:ion ro import Matplotlib's pyplot library as

.,... , - 'd of wh:11


• 1 '-' ..::.:-: n:t J r k'L ~ uu ne-c"d son11.:· , alucs. the marplotlib .pyplot module. and an t ea
~0J ''.lr.: :'", d.i:-rl.1~.

..:::.:;x-:-: ::ca:p:c:.:..i.b pyµ!ot a s pit

- -- - - - - - -
- - - - - - - - - - - -- - - - for kt1o '.\1edge
TEC ~ ', CAL Pu 6UCA TTONSS · an up-tnrvst
-
f oata sc~i:en'.:c:.::e:___ _ _ _ _ _ _(5 - 3)
~__:_ Data Visualization
_ _ _ _ _______ ______ _
dations o
f<Pn "draw" this plot in the background, but we need to bring it to the screen
.
lot w111
fhe plt.P dy after graphing everything we intend to.
, we're rea '
\\'hen . With that, the graph should pop up. If not, sometimes it can pop under, or you
5howO·
, plt. tten an error. Your graph should look like :
111aYhave go
--------- - - - - - - -.........---"--,...;.._--'---r:\....:=~=•@~aJ.i'i~J\
~ r,gur~ 1

6.5

6.0

5.5

5.0

4..5

4.0~-------------~=-------c:,'
1.0 1.5 2 .0 2 5 3 0

~ 0101+1. l,sl~l
• This Window is a matplotlib window, which allows us to see our graph, as well as interact
with it and navigate it

I 5.1.2 Line Plot


• More than 1·
a . one me can be in the plot. To add another line, just call the plot (x,y) function
gain. In th
ont h e example below we have two different values for y (yl , y2) that are plotted
0
t e chart.

ilnport Ill .
atplotlib.pyplot as plt
ilnt>ort n
Uinpy as np

ic::::: np Un
. space(-1, 1, 50)
n "' 2*}t + 1

TECHNICAL PUBLICATIONS® - an up-thrust for knowledge


' .
·•
Foundations of Data Science (5 - 4)
Data Visua/lzat/on

y2 - 2••x +1

pit .figme(num = 3, fig size = (8, 5))

plt.plot(x, y2)

plt.plot(x, yl ,

linew idth = 1.0,

lines tyle= '--'

pit.show()

• Output of the above code will look like this :

3.0
2.5
2.0
1.5
1.0
0.5
0.0
-0.5
-1 .0

- 1.00 - 0.75 - 0.50 - 0.25 0.00 0.25 0.50 0.75 1.00

Example 5.1.1 : Write a simple python program


that draws a line graph where x = [1 ,2,3,41
and y = [1,4,9, 16] and gives both axis label as ''X-a
xis" and "Y-axis".
00 Solution :

impo rtmatplotlib.pyp lot as plt

impo rtnum py as np

# defin e data value s

x - np.ar ray(l 1, 2, 3, 41) # X-ax is point


s
Y x • 2 # Y-axi s poin ts

pr1nt ("Val ues of :")

pnni ('Val uoH of Y).")

.'
I I CHNICAL PIJ/;Jl/C/\ 7 ®
IONS · n11 t1/J./h111st for knowtocl!J8
,=ou'!!!_afions <}! Data Science (5 - 5) Data Visualization

print (Y)

plt.plot(X, Y)

# Set the x axis label of the current axis.

plt.xlabel('x - axis')

# Set they axis label of the current axis.

plt.ylabel('y - axis')

#Seta title

plt.title('Draw a line.')

# Display the figure .

pit.show()

I 5.1.3 Saving Work to Disk


• Matplotlib plots can be saved as image files using the plt.savefig() function.
• The .savefig() method requires a filename be specified as the first argument. This filename
can be a full path. It can also include a particular file extension if desired. If no extension is
provided, the configuratio n value of savefig.form at is used instead.
• The .savefig() also has a number of useful optional arguments :
I. dpi can be used to set the resolution of the file to a numeric value.

2. transparent can be set to True, which causes the background of the chart to be
transparent.
3. bbox_inches can be set to alter the size of the bounding box (whitespace) around the
output image. In most cases, if no bounding box is desired, using bbox_ inches = 'tight' is
ideal.
4· If bbox_ inches is set to 'tight', then the pad_inches option specifies the amount of
padding around the image.

[fl S.1.4 Setting the Axis, Ticks, Grids


• The axes define the x and y plane of the graphic. The x axis runs horizontally, and the y
axis runs vertically.
• An ax is is added to a plot layer. Axis can be thought of as sets of x and y axis that lines and
bars arc drawn on. An Axis contains daughter attributes like axis labels, tick labe ls. and line

- lbil:k ncss.

TECHNICAL PUBLICA TIONS® - an up-thnist for knowledge


Foundations of DatR Scie nro (5 - o)
I )f1lt1 VINt1 til/t, i/1t,,i

• Thl' fo\\ rm in~ \'oc k s\w ws \ww to t,btflin


n~c css to the l\Xl! S for II plo l :
I
I fig = p\t.figu t e ()
axe s = fig .a dd axe s(\0 .1, 0 .1, 0 .8,
0 .8\) # \eft, bot. tom , wid th, h fliQhl. (Hl lllJll
() to I)
I
1 axe
s.pl ot(x , y, 'r')

, axe s.se t_xl abe l('x')

axe s.se t_yla bel( 'y')

axe s.se t title ('tit le');

Ou tpu t:

1 2 3
X 4 5
• A grid can be add ed to a Ma tplo tlib
plo t usin g the plt. grid () com man d.
By defa ul, the grid
is turn ed off. To tum on the grid use
:


\L__ __ __ __ __ __P_lt_.gn
_ 'd_(T
_ ru
_ e_) _ __
The onl y vali d opt ion s are plt. grid (Tr
_ _ _ _ __ _ _ _ __ _

ue) and plt. grid (Fa lse) . No te tha t Tru


J
e and False are
cap ital ized and are not enc lose d in quo
tes.
l!1U 5.1.5 De fin ing the Line Appearan
ce and Wo rki ng wit h Lin e Sty le
• ·
Lin e ~tylcs help ct·1t·1·erent1at
. e gra phs by dra win g the line s in var iou s way F II ving I11. ,i:
s. o O\:
1, ty k i~ use d hy Ma tplo tlib .
•j
• Ma lplo tlih has an add itio nal par ame
ter to con trol the col our and styl e of
the plot.
plt.p lot( xa, ya 'g')

TEC HNIC AL PUB LICA TION S®·


nn 11p-tl 1nist for k11o wlod go
. of oata Science (5 - 7) Data Visualization
f oundat,ons
~ '·' ••••••••••••••••••••••••••
•••• ■ •

I
-- I
- --- --- - - - - - -
I, ___ ___ ___ ___ ___ __

Fig. 5.1.1 : Line style


ta,
• This will make the line green. You can use any colour of red, green, blue, cyan, magen
yellow, white or black just by using the first character of the colour name in lower case (use
"k" for black, as "b" means blue).
be
• You can also alter the linestyle, for example two dashes -- makes a dashed line. This can
used added to the colour selector, like this:

[ plt.plot(x a, ya 'r--')

line.
• You can use"-" for a solid line (the default ),"-." for dash-dot lines, or":" for a dotted
Here is an example :
from matplot lib import pyplot as pit

import numpy as np

xa = np.linsp ace(O, 5, 20)

ya= xa**2

plt.plot(x a, ya, 'g')

Ya = 3*xa

Plt.plot(x a, ya, 'r--')

Pit.show ()

TECHNICA L PUBLICA T/ONS® - an up-thrust for knowledge


~F~ou~n~d~at~io~ns~ o~f~D~a~ta~S'.:c1~ (S _ B)
·en~c::e_ __ _ __ ~2----------
Data Visua1rza11oo
- - -------
0u tpu t:

25

20

15

10

o L o-- -- -r1- -- -- r2- -


~3- - - :4- -~ 5~
• MatPlotLib Colors are as follow
s:
Color Character
Black 'k'
Yellow ' y'
Cyan ' c'
Blue 'b'
Green 'g'
Red 'r'
White 'w '
Magenta 'm'
I 5.1.6 Adding Markers
• Markers add a special symbol to
each data point in a line graph. Un
markers tend to be a little less suscep like line style and color,
tible to accessibility and printing
issues.
• Basically, the matplotlib tries
to have identifiers for the markers
marker : which look similar to tbe

1. Triangle-shaped : V, < , > , /\


2. Cross-like : * , + , 1 , 2 , 3 ,
4
3. Circle-like : o , . , h , p , H ,
8

TECHNICAL PUBLICAT/ONS®
- an up-thrust for knowledge
_ -- ~ -:; !);:3 S,;:en.::e (5 - 9 Data Visualization
- - - - --
~_,_r,:.::-L' _:_-- -- - - - - - - - - - - - - - - - - - - - - - - - - - -

... ~::::s.
::a,:=~
~~
- - c::"e-rentiy shaped mari.:crs - ish between differen t -groups of
is a grear way to clisrinru
ff your control gTOLrp is all circ!~ and your experime ntal group is all X's the
;::::;·~e=~ pops oUL c Yai to colo:-blind \iewa-s.

• T: o:-e·s way to specify multiple marker s-ryles in a single scanerO call. but we can
:10

s...~u: our data om into groups and plot each marker style separate ly. Here we chopped
or ciara up into three equal groups.

1.5
X
• -•

1.0

0 .5


-· X
X ,
• •

••

xx

• •
0.0 •
X


•••
X

X X X
- 0 .5 •• ••• X X

- 1.0 • Xx

• •
- 1.5 • X
• •
- 1.00 - 0 .75 - 0 .50 - 0.25 0 .00 0 .25 0.50 0.75 1.00

I s.1.1 Using Labels, Annota tions and Legend s


• TO fully documen t your graph, you usually haYe to resort to labels. annotati ons. and
legends. Each of these elements has a different purpose. as follows :
I. Label: Make it easy for the \ iewer to know the name or kind of data illustrate d
-
...
2· Annotat ion : Help extend the ,iewer's knowled ge of the data. rather than simply
identify it.
}
3· Legend : Provides cues to make identification of the data group easier.

TECHNICAL PUB LJCA T10N~ - an up-Ulrust for knon'edge


'


Foundations of Data Science (5 - 10)
Data Visualization
• The following example shows how to add labels to your graph :

values = (1, 5, 8, 9, 2, 0, 3, 10, 4, 7)


impor t matpl otlib.p yplot as plt

plt.xla bel('En tries')

plt. ylabel ('V alues')

plt.plo t(rang e(l, 11), values )

plt.sho w()

• Following example shows how to add annotation to a graph :

impor t matpl otlib.p yplot as plt

w=4

h=3

d = 70
plt.fig ure(fig size=( w, h), dpi=d )

plt.axi s([O, 5, 0, 51)

X = (0, 3, 5)

y = (1, 4, 3 .5)
label x = 1

label_ y = 4

arrow_x = 3

arrow _y = 4

arrowyrope rties = diet(

faceco lor= "black" , width =0.5,

headw idth=4 , shrink = 0.1)

plt.an notate ( "maxim um", xy=(a rrow_x , arrow_y),

xytex t =(label_ x, label_ y),

arrow props =arrow_prope rties)

plt.plo t(x, y)

plt.sav efig ( II out .png ")

TECHN ICAL PUBLIC A TIONs® - an up-thrus t for knowled ge


f oata Science (5 - 11) Data Visualization

cnunda~
~
0otpt1I : 5 r--- --.- ---- ,.... ---.----- .--- ---,
Maximum---..._
4

00 1 2 3 4 5

Creating a legend
rance and behavior of the plot
• There are several options available for custo mizin g the appea
multiple series and only
legend. By default the legen d always appea rs when there are
lt the legend shows point
appears on mouseover when there is a single series. By defau
e leaves.
values when the mous e is over the graph but not when the mous
line is presented in a table that
• A legend documents the individual elements of a plot. Each
line.
contains a label for it so that peop le can differentiate between each
import matpl otlib.p yplot as plt

import nump y as np

x = np.lin space (-10, 9, 20)


Y=x ** 3

Z = X ** 2

figure == plt.fig ure()

axes== figure .add axes([ 0,0,1,1 ])

axes.plot(x, z, label= "Squa re Funct ion")

axes.p lot(x, Y, label= "Cube Funct ion")


axes .legen d()
1 . x, y and z vana · bl es. ,11
· above we define two functions : square and cube usmg
In the scnpt · ~1
Next fi pass the value Square \,
' we irst plot the square function and for the label parameter, we
Function.

TECHN ICAL PUBLIC A T/ONS® - an up-thrust for knowled


ge
'.I
Fo1111dntio11s of 011111 Sdol lGU (5 - 12) Data Visualization

• \'his will lw tlw valu~ displnyl:d in thl: labl:I for


squarn runction . Next, we plot the cube
lt11Klil'1\ ;\IHI pass l 'ubl: Fund ion as vulue for the
label parameter.
• \'lw l,111p111 lo0ks likes this :
750
.- - _- _
..-.---_
-
_-
- -.--_
--.--_,- - - - - - - - - -,
Square function
- Cube function
500

250

-250

- 500

- 750

1000
-10 .0 -7.5 -5.0 -2.5 0.0 2.5 5.0 7.5
(Il 5.2 Scatter Plots
• A scatter plot is a visual representation of how
two variables relate to each other. we can
use scatter plots to explore the relationship between
two variables, for example by looking
for any c01Telation between them.
• Matplotlib also supports more advanced plots
, such as scatter plots. In this case, the
scatter() function is used to display data values
as a collection of x, y coordinates
represented by standalone dots.
impo rtma tplot lib.p yplo t as plt

# X axis values:

X = 12,3,7,29,8,5, 13,11,22,33]
# Y axis valu es:

y = [4,7,55,43,2,4,11,22,33,44]

# Crea te scat ter plot:

plt.s catter(x, y)

pit.s how ()

TECHNICAL PUBLICATIONS® . an up-thrust for


knowledge
. ns of
foundat,o
Data Science
--=- ---- ---- -----
(5 - 13)
--....:..____ ___ ____ ____ __tion
Data Visualiza _

comparing plt.scatterO and pit.plot() : We can also produce the scatter plot shown above
• using another function within matplotlib.pyplot. Matplotlib ' splt.plot() is a general- purpose
plotting function that will allow user to create various differen t line or marker plots.
, We can achieve the same scatter plot as the one obtained in the section above with the
following call to pit.plot(), using the same data :

l p!t.plot(x, y , "o")

~ It.show()

, In this case, we had to include the marker "o" as a third argument, as otherwis e pit.plot(
)
would plot a line graph. The plot created with this code is identical to the plot created
earlier with pit.scatter().
• Here's a rule of thumb that can use:
a) If we need a basic scatter plot, use pit.plot() , especially if we want to prioritiz e
performance.
b) If we want to customi ze our scatter plot by using more advance d plotting features , use
plt.scatter().
• Example : We can create a simple scatter plot in Python by passing x and y values to
pit.scatter() :

# scatter_ plotting. py

importma tplotlib.p yplot as plt

Pit.style. use('fivet hirtyeigh t')

X: (2,4, 6,6, 9,2, 7, 2, 6, 1,8,4, 5, 9, 1, 2, 3, 7, 5, 8, 1, 3)

y : (7,8,2,4 , 6,4,9, 5,9,3,6, 7,2,4,6, 7, 1, 9,4,3,6, 9]

Plt.scatte r(x, y)

Pit.show( )

TECHNICA L PUBLICATI ONS® - an up-thrust for knowledge


Foundations of Data Science (5 - 14) DflltJ VISUlll/lallon

Output:

1.
2 3 4 5 6 7 8 9

I 5.2.1 Creating Advanced Scatterplots


• Scatterplots are especially important for data science because they can show data patterns
that aren't obvious when viewed in other ways.
import matplotlib.pypl ot as plt
x_axisl = (1, 2, 3, 4, 5, 6, 7, 8, 9, 101
y a.xisl= [5, 16, 34, 56, 32, 56, 32, 12, 76, 891
x_axis2 = (1, 2, 3, 4, 5, 6, 7, 8, 9, 101
y_ axis2 = [53, 6, 46, 36, 15, 64, 73, 25, 82, 91
plt.title("Prices over 10 years")

plt.scatter(x_a xisl, y_axisl, color='darkblue ', marker= 'x', label= "item 1")

plt.scatter(x_axis2, y_axis2, color='darkred', marker = 'x', label= "item 2")


plt.xlabel("Time (years)")
plt.ylabel("Price (dollars)")
plt.grid(True)
plt.legend()

pit.show()

• The chart displays two data sets. We distinguish between them by the colour of the marker.

IJJ 5.3 Visualizing Errors


- - -- - - - - - - - - -- - - - - - - - - -- ------ ------
• Error bars are included in Matplotlib line plots and graphs. Error is the difference between
the calculated value and actual value.
TECHNICAL PUBLICATIONS® - an up-thrust for knowledge
00 ~ s of Data Science (5 - 15) Data VIBuaflzutlon
~
Without error bars, bar ~apbs provide th~ perception that a meas urable or detcrminc<l
1
number is defined to a high level of efficiency. The method matplotl ib.pyplot.c rrorbar()
draws y vs. x as planes and/or indicators with error bars associated.

1
Adding the error bar in Matplotli b, Python. It's very simple, we j ust have to write the vtt luc
of the error. We use the command :
plt.errorba r(x, y, yerr = 2, capsize = 3)

\\nere :
x == Toe data of the X axis.
y == Toe data of the Y axis.

yerr = The error value of the Y axis. Each point has its own error value.
xerr = The error value of the X axis.
capsize= Toe size of the lower and upper lines of the error bar
• A simple example, where we only plot one point. The error is the IO % on the Y ax is.
importmatp lotlib.pypl ot as plt
x =l
y = 20

y_error = 20*0.10 ## El 10% de error


ph.errorbar{ x,y, yerr = y_error, capsize= 3)
Ph.show()

Output:

22.0

21 .5

21 .0

20.5

20.0

19.5

19.0

18.5

18.0 L -...,..- ----.-- ---:~--


1.00
:~ -----:~ -~
0.98 1.02 1.04
0.96
T/ONS® - an up-thrust for knowledge
TECHNICAL PUBUCA
Foundations of Data Science (5 - 16) Data Visualization

• We plot using the command "plt.errorbar ( .. .)", giving it the desired characteristics.

importmatplotlib.pyplot as plt

importnumpy as np

x = np.arange(1,8)

y = np.array([20,10,45,32,38,21 ,27])

y_error = y * 0.10 ##El 10%

plt.errorbar(x, y, yerr = y_error,


linestyle="None" , frnt = "ob", capsize= 3, ecolor="k")

plt.show()

• Parameters of the errorbar :


a) yerr is the error value in each point.
b) linestyle, here it indicate that we will not plot a line.
c) fmt, it is the type of marker, in this case is a point ("o") blue ("b").
d) capsize, is the size of the lower and upper lines of the error bar.
e) ecolor, is the color of the error bar. The default color is the marker color.
Output:
50

45 -

40 -

35
I t
30

25

20

15
!
10 !
I I 7
1 2 3 4 5 6 7

TECHNICAL PUBLICATIONS® - an up-thrust for knowledge


. of Data Science (5 - 17) Data Visualization

~ .
lti le lines in MatplothbErrorbar in Python : The ability to draw numerous lines in
, Mu P . .. , . .
t the same plot ts cnttca1. We 11 draw many errorbars in the same graph by usmg this
altnos
schern__e_._ - -- - - -- -- - - - - - - - - - - - - - - - - - - - - ,
unportnumPY as np

unportmatplotlib.pyplot as plt

fig = plt.figure()
x = np.arange(20)

y = 4 * np.sin(x / 20 * np.pi)

yerr = np.linspace(0.06, 0 .3, 20)


plt.errorbar(x, y + 8, yerr = yerr,)

plt.errorbar(x, y + 6, yerr = yerr,

uplims =True,)

plt.errorbar(x, y + 4, yerr = yerr,

uplims = True,
lolims = True, )

upperlimits = [True, False] * 6

lowerlimits = [False, True] * 6

plt.errorbar(x, y , yerr = yerr,

Uplims = upperlimits,
10lims = lowerlimits, )

Plt.legend(loc ='upper left')

Plt.title('Example')

Plt.show()

TECHNICAL PUBLICATIONS® - an up-thrust for knowledge


Foundations of Data Science (5 - 18) Data Visualization

Output:

0.0 2.5 5.0 7 .5 10.0 12.5 15.0 17.5

W 5.4 Density and Contour Plots


• It is useful to display three-dimensional data in two dimensions using contours or color-
coded regions. Three Matplotlib functions are used for this purpose. They are :
a) pit.contour for contour plots,
b) plt.contourf for filled contour plots,
c) plt.imshow for showing images.
1. Contour plot :

• A contour line or isoline of a function of two variables is a curve along which the
function has a constant value. It is a cross-section of the three-dimensional graph of the
function f(x, y) parallel to the x, y plane.
• Contour lines are used e.g. in geography and meteorology. In cartography, a contour line
joins points of equal height above a given level, such as mean sea level.
• We can also say in a more general way that a contour line of a function with two
variables is a curve which connects points with the same values.

import numpy as np

xlist = np.linspace(- 3.0, 3.0, 3)

ylist = np.linspace(- 3.0, 3.0, 4)

TECHNICAL PUBLICATIONS® - an up-thrust for knowledge


. of oata Science (5 - 19) Data Visualization
5

~ -=--=--=---=----=----=----=---=--=--=--=--=--=--=--=--=--=--=--=--=-~-=--=--=-~-=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=-~~~~~~~~~
){, y == np.rneshgrid(xlist, ylist

print(xliSt)

print(ylist)

print(X)

print(Y)

output :
[ - 3. 0. 3. ] Corresponds to the
following co-ordinate
[ - 3. - 1. 1. 3.]
points:
[ [ -3. 0. 3.]
[ -3. 0. 3. ]
(-3,- 3) (0, - 3) (3,-3)
[ -3 . 0. 3. ]
(- 3,-1) (0,-1) (3, - 1)
[ - 3. 0. 3. ] ]
(- 3, 1) (0, 1) (3, 1)
[ [ -3. -3. -3. ]
(- 3, 3) (0, 3) (3, 3)
[ - 1. - 1. - 1. ]
[ 1. 1. 1. ]
[ 3. 3. 3. ]]
Changing the colours and the line style

importmatplotlib.pyplot a s plt

Pit.figure()

cp = plt.contour(X, Y, z, colors='black', linestyles='dashed ')

Plt.clabel(cp, inline = True,

fontsize= 10)

Plt.title('Contour Plot')

Plt.xlabel('x (cm)')

Pit.Ylabel('y (cm)')

Pit.show()

-------- -----;:;:----~ ---:--:---------


TECHNICAL PUBLICATIONS® - an up-thrust for knowledge
Pounclo tlon:-: of Datn Sclonw (5 - 20) Data V/8 u811,~ ,
1
"""'on

Output: cont.our plot

• When creating a contour plot, we can also specify the color map. There are different c)a<Jses
of color maps. Matplotlib gives the following guidance:
a) Sequential : Change in lightness and often saturation of color incrementally, often using
a single hue; should be used for representing information that has ordering.
h) Diverging : Change in lightness and possibly saturation of two different colors that
meet in the middle at an unsaturated color; should be used when the information being
plotted has a critical middle value, such as topography or when the data deviates around
zero.
c) Cyclic : Change in lightness of two different colors that meet in the middle and
beginning/end at an unsaturated color; should be used for values that wrap around at the
endpoints, such as phase angle, wind direction, or time of day.
d) Qualitative ·: Often are miscellaneous colors; should be used to represent information
which does not have ordering or relationships.
th
• Th'is d ata h'as b ot h pos1t1ve
· · and negative
· values which zero representing · a node for e
wave fiunction.
. There are three important
· '
display options for contour plots : the undisplaced
shape key, the scale factor, and the contour scale. .
10
. Iace d shape option controls if and how the deformed model 15
a) Th e disp · 5hown. he
. nl " is t
comparison to t~e undeformed (original) geometry. The "Deformed shape o Y
default and provides no basis for comparison. aJl

b) The "Deformed shape with undeformed edge" option overlays the contour plot on
outline of the original model
. tbe
c) The "Deformed shape with undeformed mod l" t· l the contour plot on
. . . · e op 10n over ays
ongmal fimte element model. ~

TECHNICAL PUBLICA TfONs®


• an up-thrust for knowledge
S -2·

:,:"tbJt category .
1

~h<.,w inf th ..' num tx'r l,f \int~l i"'in t~


, :: pro,i des a , isua l inter pret ation of mm1c-ric-al dam 1'y
chat fall "ith in a spec ified rang e of Yalu ~ called
..bins".

, Fig. 5.5.1 show s histo gram .


Exam ple t·sto ~ram daily steps taken

100

80

c 60 ..,
::I C:
0 ::I
C.) 0
u
C:
CD
40

20
Bin 2

40~0=-=o:-1
"'"00-=-_._---:-3-:i~!';O:'"'.o:---==---
0 L.1--==-=L .-- 1 - -L-2-o.._o_o~L--2-s'-o--o..-J1---3~0
10 0 0 15 0 0
Daily steps taken
Bin 2 starti ng point
Fig. 5.5.1 : Hist ogra m

• H"1st the frequ ency tlf th~- dutn vah1 cs. The
ograms can disp lay a larg e amo unt of data and
rmin ed hy a histog,rnm . In addi tion . it can
rnedian and distr ibuti on of the data can be dete
show any outli. ers or gaps in the data .
,I
pute nnd d ispla y histn grnm s : pit .hist ()
•j•
• Matplotlib prov ides a dedi cate d func tion to com

for k11owledgo
TECH NICAL PUBL ICA T/ONS® • on 11p-thn isl
Foundations of Data Science (5 - 22) Data Visualization

• Code for creating histogram with randomized data :


import nurnpy as np

import matplotlib.pyplot as plt

x = 40 * np.random.randn(50000)

plt.hist(x, 20, range=(-50, 50), histtype='stepfilled',

align='mid', color='r', label='Test Data')

plt.legend()

plt.title(' Histogram')

plt.show()

IJJ 5.6 Legend


• Plot legends give meaning to a visualization, assigning labels to the various plot elements.
Legends are found in maps - describe the pictorial language or symbology of the map.
Legends are used in line graphs to explain the function or the values underlying the
different lines of the graph.
• Matplotlib has native support for legends. Legends can be placed in various positions: A
legend can be placed inside or outside the chart and the position can be moved. The
legendQ method adds the legend to the plot.
• To place the legend inside, simply call legendQ :
import matplotlib.pyplot as plt

import numpy as np

y = (2,4,6,8, 10, 12, 14, 16, 18,20]

y2 = [10,11,12,13,14,15,16,17,18,19]

x = np.arange(10)

fig = plt.figure()

ax= plt.subplot(111)

ax.plot(x, y, label= '$y = numbers')

ax.plot(x, y2, label= '$y2 = other numbers')

plt.title('Legend inside')

ax.legend()

plt.show()

TECHNICAL PUBLICA TIONs® - an up-thrust for knowledge


f oata Science (5 - 23) Data Visualization
dsfions o
~
output :
d=
d ~in=sci=
= e =:::r::::=:=:!===::::::c==::::::::7J
20 1 _--r ---. ---- r--L_e,g~e~n
$y = numbers
18 - $y2 = other numbers

8 9

, If we add a label to the plot function, the value will be used


as the label in the legend
on: We can define
command. There is anoth er argum ent that we can add to the legend functi
the location of the legen d inside of the axes plot with the parameter
"loc". If we add a label
to the plot function, the values will be used in the legend command :
fromp olynom ialsim portPo lynom ial

impor tnump yasnp

impor tmatpl otlib.p yplota splt

P==Polynomial(-0.8 ,2.3,0 .5, 1,0.2)

P_der==p .deriva tive()

fig,ax==plt.su bplots ()

X==np.linspa ce(-2,3 ,50,en dpoin t=Tru e)


F==p(X)

F_deriv ative = p der(X)

ax.Plot(X ,F ,label = "p")


it
ax.plot (X,F_ deriva tive.la bel= "deriv ation of p") JI
,.
ax.Iege nd(loc = 'upper left')

TECHNICAL PUBLICATIONS® - an up-thrust for knowledge


Foundations of Data Science (5 - 24) Data Visuafizat·
ion
Output:

p
derivation of p

Matplotlib legend on bottom

importmatplotlib.pyplotasplt

importnumpyasnp

y = (2,4,6,8, 10,12, 14, 16, 18,20)

y2 = [10,11,12,13,14,15,16,17,18,19)

x = np.arange{10)

fig = plt.figure{)

ax= plt.subplot{111)

ax.plot(x, y, label='$y = numbers')

ax.plot(x, y2, label='$y2 = other numbers')

plt.title('Legend inside')

ax.legend{loc='upper center', bbox_to_anchor={0.5, -0.05),&nbsp;


shadow=True, ncol=2)

plt.show()

TECHNICAL PUBLICA TIONs® - an up-thrust for knowledge


. of oata Science (5 - 25) Data Visuallzation

~
output:
nd
eg:;.:e.:..:.
L-=
20 , - . . - - - - - - - ins
:.....:..:..: .:::::___
=:i:de _ _ _ __

18

16

14

12

10

2 3 4 5 6 7 8 9

I- Sy = numbers - Sy2 = other numbers I


(Il 5.7 Subplots
• Subplots mean groups of axes that can exist in a single matplotlib figure. subplotsO
function in the matplotlib library, helps in creating multiple layouts of subplots. It provides
control over all the individual plots that are created.
• subplotsO without arguments returns a Figure and a single Ax.es. This is actually the
simplest and recommende d way of creating a single Figure and Ax.es.
fig,ax=plt.subp lots()

ax.plot(x,y)

ax.set title('A single plot')

Output:
A single plot

1.00

0.75

0.50

0.25

0.00

-0.25

-0.50

-0.75 ,.
I

I,

0 2

TECHNICAL PUBLICATIONS® - an up-thrust for knowledge

You might also like