0% found this document useful (0 votes)
2 views21 pages

Data Visualization Using Pyplot

Uploaded by

bruhhstudyy
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)
2 views21 pages

Data Visualization Using Pyplot

Uploaded by

bruhhstudyy
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/ 21

Data Visualization

8
using Pyplot
In Tis Chapter
8.1 What is Data Visualization ?
8.2 Using Pyplot of Matplotlib Library
8.3 Creating Charts with Matplotlibs Library's Pyplot Interface

8.4 Customizing the Plot

8.5 Comparing Chart Types

8.1 WHAT IS DATA VISUALIZATION?


Modern age has become very fast and competitive with the pace of the development in all fields
of life. The reach of all businesses and facilities have gone global because of the modern
technologies. This has made things easier and competitive but at the same time data have
increased multifold. In fact, data have grown so big that a specific term has been coined, big
data'.
As you all are aware that the role of data is to empower decision makers to make decisions
based on facts, trends and statistical numbers available in theform of data. But since data is so
huge these days that the decision makers must be able to sift through the unnecescarm:
unwanted data and get the right information presented in compact and apt way, so that they
can make the best decisions. For this purpose, data visualization techniques have gained
visualization? Well, read
Confused? What is this data
on.
Popularity.
Data visualization basically refers to the graphical or visual represerntation of information and
data using visual elements like charts, graphs, and maps etc. LData visualization is immensel
useful in decision making. Data visualization unveils patterns, trends, outliers, correlations ete in
the data, and thereby helps decision makers understana tne meaning ot data to drive business

decisions.
285
286 COMPUTER SCIENCE WITH PYTHONY
A

For instance, a company has to decide about, which advertising solution should it invest
1vest in to
promote its new product" Data visualization is here to help just pull out data of comnan
previous campaigns, and plot a bar chart comparing the pertormance of difterent platforms pany's
ms and
bingo! the right decision is right in front. DATA VISUALIZATION
This chapter is dedicated to get you started with data Data
visualization basically
visualization using Python's usetul tool PyPlot where you refers to the
graphical or visual
shall learn to represent data visually in various forms such representation of information
and data using visual
as line, bar and pie charts etc. So, let's get started. elements
like charts, graphs, and
maps
etc.
S.2 USING PYPLOT OF MATPLOTLIB LIBRARY
For data visualization in Python, the Matplotlib library's Pyplot interface is used.
Ihe matplotlib is a Python library that provides many interfaces
NOTE
and functionality for 2D-graphics similar to MATLAB 's in various
forms. In short, you can call matplotlib as a high quality plotting PyPlot is a collection of
library of Python. It provides both a very quick way to visualize methods within matplotlib
data from Python and publication-quality figures in many formats. library (of Python) which
allow user to construct 2D
The matplotlib library offers many different named collections of plots easily and interactively.
methods; PyPlot is one such interface.
PyPlot is a collection of methods within matplotlib which allow user to construct 2D plots
easily and interactively. PyPlot essentially reproduces plotting functions and behavior of
MATLAB.

8.2.1 Installing and Importing matplotlib


You shall learn to plot data
using PyPlot but before that make sure
that matplotlib library is installed on NOTE
computer.
your
If you have installed
Python using Anaconda, then matplotlib The matplotlib library is
library is already installed on your computers. You can check preinstalled with Anaconda
it yourself by distribution; you need not
starting Anaconda Navigator. From Navigator
window, click Environments and then scroll install it separately if you
down in the have installed Python using
alphabetically sorted list of installed packages on your Anaconda distribution.
computer. You will find matplotlib there.
If you have installed Python using standard official
matplotlib separately as explained here. distribution, you may need to install
First you will need to download
wheel package of
version installed and the matplotlib as per Python s
installed.
platform (MacOs
For this go to the link
or Windows or Linux) on which it 5
download required wheel package https://pypi.org/project/matplotlib/zfiles
as
per your platform.
and

Next you need to install


it by giving following commands
python -m pip install -U pip
python -m pip install -U matplotl ib
MATLAB is a
high-performance language for
and technical computing. It integrates zation,
programming in an
easy-to-use environment where computation, vi5uailiar
mathematical notation. problems and solutions are expressed in
id
286 COMPUTER SCIENCE WITH PYTHON - XII

For instance, a company has to decide about, which advertising solution should it invest in
promote its new product?" Data visualization is here to help - just pull out data of companv'e
to

previous campaigns, and plot a bar chart comparing the performance of different platforms nd
bingo! the right decision is right in front.
DATA VISUALIZATION
This chapter is dedicated to get you started with data Data visualization basically
visualization using Python's useful tool PyPlot where you refers to the graphical
representation of information
or
visual
shall learn to represent data visualy in various forms such
and data using visual
as line, bar and pie charts etc. So, let's get started.
ike charts, graphs, and
elements
etc.
maps
8.2 USING PYPLOT OF MATPLOTLIB LIBRARY
For data visualization in Python, the Matplotlib library's Pyplot interface is used.

The matplotlib is a Python library that provides many interfaces


and functionality for 2D-graphics similar to MATLAB's in various
NOTE
torms. In short, you can call matplotlib as a high quality plotting PyPlot is a collection of
library of Python. It provides both a very quick way to visualize methods within matplotlib
library (of Python) which
data from Python and publication-quality figures in many formats. allow user to construct 2D
The matplotlib library offers many different named collections of plots easily and interactively.
methods; PyPlot is one such interface.
PyPlot is a collection of methods within matplotlib which allow user to construct 2D plots
easily and interactively. PyPlot essentially reproduces plotting functions and behavior of
MATLAB.

8.2.1 Installing and Importing matplotlib


You shall learn to plot data using PyPlot but before that make sure
that matplotlib library is installed on your computer. NOTE
If you have installed Python using Anaconda, then matplotlib The matplotlib library s
preinstalled with Anaconda
library is already installed on your computers. You can check
distribution; you need not
it yourself by starting Anaconda Navigator. From Navigator install it separately if you
window, click Environments and then scroll down in the have installed Python using
alphabetically sorted list of installed packages on your Anaconda distribution.

computer. You will find matplotlib there.


If
you have installed Python using standard official distribution, you may need to install
matplotlib separately as explained here.
First you will need to download wheel package of matplotlib as per Python's
version installed and the platform (MacOs or Windows or Linux) on which it is
installed. For this go to the link https://pypi.org/project/matplotlib/#files and
download required wheel package as per your platform.
Next you need to install itby giving following commands
python -m pip install -U pip
python-m pip install -U matplotlib

on
MATLAB is a high-performance language for technical computing. It integrates computation, visualizdar
and programming in an easy-to-use environment where problems and solutions are expressed in lau
mathematical notation.
DATA VISUALIZATION USING PYPLOT
Chapter 287
Anaconda Navigator

ie Belp
You may also type
ANACONDA NAVIGATOR matplotlib here to
pgrade tio quickly search it here
Home
e nton ents
Installed Channels updateindex
nvironierits base (root)
iame T, Description
version

Projects (beta) 2.19

Implements a xm/html/shtmi markup safe


merkupsefe
Learning Scroll down in this string for python

alphabetically sorted list matplotlib Python 2d plotting library


of installed
&Community packages to rnccabe
look for matplotlib OMccabe complexity checker for python 0.6.1

menuinst Cross platform menu item ins talla tion 14.11

Documentation
mistune The fastest markdown parser in pure
python with renderer feature
0.8.3

Developer Blog mkl Math library for intel and compatible


2913 0
processors

Feedbac mkl-service Python bindings to mkl service Functions 1.1.2

mpmath Pythonlibraryfor arbitrary-precision


rloating-point arithmetic 1.0.0

Create Import 221 packages available

Importing PyPlot
In order to use pyplot on your computers for data visualization, you need to first import it in
your Python environment by issuing one of the following commands:

This would require you to refer to every


import matplotlib.pyplot command of pyplot as
matplotlib.pyplot. <command>

With this, you can refer to every command of pyplot as


import matplotlib.pyplot as pl
pl. command>
as you have given an alias name to matplotlib.pyplot as pl

With the first command above, you will need to issue every pyplot command as per following

syntax
matplotlib.pyplot.<command
But with the second command above, you have provided pl as the shorthand for
invoke PyPlot's methods as this
matplotlib.pyplot and thus now you
can

pl.plot (X, Y)
Oucan choose any legal identifier in place of pl above.

6.2.2 Working with PyPlot Methods


The PyPlot interface provides many methods for 20 plotting of data. The matylotlib's
yplot interface lets one plot data in multiple ways such as line chart, bar chart, pie chart, scatter
Chart etc. ILet us talk about how you can plot sequence or array of data using PyPlot methods.
R : DATA VISUALIZATION USING PYPLOT
Chopter 287
AnacondaNavigafor
File Help
You may a'so type

ANACONDA NAVIGATOR matplotlib here to


quickly search it here

Home
me
nsa Channes update inde

nvironmerits base (roo


eme Descriotio

Projects (beta)
merkuDafe pilementsmhtmiihei eru sete
string for pechon
Learning Scroll down in this
alphabetically sorted list matpiob Pthon 2 piotting rary

Community ofinstalled packagesto mecabe M c c a b e compieiy e c e r tor pyton


look for matplotlib
menuinst Crosspiatformmenu item instalation

Documentation The Festest marikdown erser in pure


mis bune Python with renderer Feature

Mahrery Forintel and competibe


Developer Blog
proceses

Feedbac mil-ervice Python bincings to mil serice functions

Pythen rany for areitrar-pre cisicn


mpmeth Floating-pcint arithmetic

Create import 221 pacages erzlable

Importing PyPlot
In order to use pyplot on your computers for data visualization, you need to first import it in
your Python environment by issuing one of the following commands :

This would require you to refer to ever


import matplotlib.pyplot command of pyplot as
matplotlib.pyplot. <command>

With this., you can refer to every command of pyplot as


importmatplotlib.pyplot as pl
pl. <command>
as you have given an alias name to matplotlib.pyplot as p

With the first command above, you wil need to issue every Pyplot command as per following

syntax
matplotlib.pyplot.<command>
But with the second command above, you have provided pl as the shorthand for
can invoke PyPloe's methods as this:
atplotlib.pyplot and thus now you

pl.plot(X, Y)
TOu can choose any legal identifier in place of pl above

8.2.2 Working with PyPlot Methods


tor 20 plotting of data. The matplotlib's
he PyPlot provides many methods
interface
such as lime chart, bar chart, pie chart, scatter
yplot interface lets one plot data in multiple ways
nart etc. Let us talk about how you can plot sequence or array of data using PyPlot methods.
288 COMPUTER SCIENCE WITH
PYTHON .

XIL
But before we proceed with it, I shall recommend you to have an idea ul using NumPu
ing NumPy library
and some of its functions, for these two reasons, specifically :

(7) NumPy offers some other useful functions to create arrays of data, which prova.
while plotting data. useful
(1) NumPy offers many useful functions and routines.
(11) NumPy arrays which are like lists, support vectorized operations, i.e, if you.
function, it is performed on every item (element by element) in the array unlike lida apply
Let's suppose you want to add the number 2 to every item in the list or array and if1u
eg
you
give an expression such as List +2 (where List is a Python list), Python will give rror
but not with NumPy array. For a NumPy array, it will simply add 2 to each element of
the NumPy array.
This feature may prove very useful in ploting. e.g, if you have a NumPy array namelu
X (say, ((1,2,3, 41) ), and you want to compute sin() for each of the values of this ara
for plotting purpose, you just need to write is numpy.sin(X)

For these reasons, I recommend that you should know how to create NumPy arrays and
NumPy functions on them. Following section briefly introduces how to create and use NumBe
arrays.

8.2.2A Using NumPy Arrays


NumPy ('Numerical Python' or 'Numeric Python', pronounced as Num Pie) is an open Source
module of Python that offers functions and routines for fast mathematical computation on
arrays and matrices. In order to use NumPy, you must import in your module by using a
statement like:
You can use any identifier name in place of np but np has
been a preferred choice, generaly
import numpy as np

The above import statement has given np as an alias name for NumPy module. Once imported
with as <name>, you use both names i.e., numpy or np for functions e.g., numpy.array() is same
as np.array().
Array in general refers to a named group of homogeneous NOTE
(of same type) elements. For example, if you store the Please note that if you have

similar details of all sections together such as if you store installed Python through
Anaconda installer then NumPy,
number of students in each section of class X in a school, e.g,
SciPy, Pandas, Matplotlib etc. are
Students array containing 5 entries as [34, 37, 36, 41, 40] then by default installed with Python,
Students is an array that represents number of students in otherwise you need to install
each section of class X. Like lists, you can access individual these separately through PIP

elements by giving index with array name e.g, Students[1] installer of Python.

will give details about 2 section, Students[3] will give you


details about 4" section and so on.
You
A NumPy array is simply grid
a that contains values of the same/homogeneous type
can think of a NumPy array like a Python list having all elements of similar types (but Nunt
arrays are different from Python lists in functionality, which will be clear to you in con
lines).
Chapter 8 : DATA VISUALIZATION USING PYPLOT

289
Consider following code

Code Now,you can use numpy junctions either as

Indices 0 1 2 3
import numpy as np numPy.function Name or np.function Name
e.g, nanpy.array() or np.array( )
List [ 1, 2, 3, 4]
Data al np.array(List)) It will create a
NumnPy array Jrom
the given list
Inside memory print(a1)
In 13]: import numpy as np Jupyter Untitled11
Logcut
File Edt
In [14]: List [1, 2, 3, 4] ew nsert e Kenel idgets Trusted P,thon s
+
In [15]: a1 =np.array (List) Run C Code
In
[2] import numpy 3s np
In [16]: al
Out [16]:array( [1, 2, 3, 41) In [4: List - [1, 2, 3, 4
al np.array(List)
In [17]: print (a1)
1 2 3 4] In 7 : a

Out(7 array ([1, 2, 3, 4])


Notice how it displays array and In
[8 Print (31)
how it prints it with print()
23 4

Individual elements of above array can be accessed just like you access a list's, i.e.,
Karray-name> [ <index>]
That is, a110] will give
you 1, al[1] will give you 2,..al3] will give you4.
rollowing Fig. 8.1 illustrates the basic terms associated with a NumPy array:
axis= 1
axis 2
10 0 he axes of an The shape of an
010 array describe array is a tuple
00 1 the order of indicating the All elements must be of
number of elements the same dtype (datatype)
1 0 0 indexing into the
array, e.g., axis = 0 along each axis. An
01 0 refers to the first existing array a has The default dtype is float
00 1 index coordinate an attribute a.shape in an NumPy array
1 0 0 axis = 1 the which contains
0 1 0 second, etc. this tuple

Shape (8, 3)
Figure 8.1 Anatomy of a NumPy Array

check the type of objects in Python,


Can check type of a NumPy array in the same way you
y USing type(). Also, there are associated attributes: (1) shape that returns dimensions of a NumPy

array
ay and (ii) itemsize that returns the length of each element ot array
in bytes. (see below)

In it returned tor NumPy arrays you created


[25]: type (a1), type(a2) See the type
Out4 (numpy. ndarray, numpy . ndarray)

In [26] al.shape the dimensions of a NumPy array. For 1D


The shape attribute gives
Out[26]: (4,) array, see it returned as (4,)Le., 4 elements, single index only
In [27]: a2.shape returned both dimensions.
For 2D arrays, it
Out
[27]: (2, 3)
In [28]: a2.itemsize
The itemsize attribute returns
the length of each element ofarray in bytes
Out | 28]: 4
COMPUTER SCIENCE WITH PYTHON
THON XI
290
You can check data type ot a NumPy array's elements using In [11]: a1.dtype
<arrayname>.dtype c.g., (see on the right) Out [11]: dtype("int32")
Some common NumPy data types (used as numpy.<datatype>)
are being given on Table 8.1. NOTE
Table 8.1 NumPy Data Types Numpy arrays are also called
ndarrays
S.No. Data Type Description Size
1. numpy.int8 Stores signed integers in range -128 to 127
byte
2. numpy.int16 Stores signed integers in range -32768 to 32767 2 bytes
numpy.int32 Stores signed integers in range -2t to 2b-1 4 bytes
numpy.int64 Stores range -2 to 2-1
signed integers in 8 bytes
O. numpy.float_ Default type to store floating point (floató4) 8 bytes
6. numpy. float16 Stores half precision floating point values 2 bytes
(5 bits exponent, 10 bit mantissa)
7. numpy.float32 Stores single precision floating point values 4 bytes
(8 bits exponent, 23 bit mantissa)
8. numpy.float64 Stores double precision floating point values 8 bytes
(11bits exponent, 52 bit mantissa)
Some usetul ways ot creating NumPy arrays
() Creating arrays with a numerical range using arange( ). The arange() function is similarto
Python's range() function but it returns an ndarray in place of Python list returned by rangel) of
Python. In other words, the arange() creates a NumPy array with evenly spaced values within a
specified numerical range. It is used as:
<arrayname> = numpy.arange( [start, ] stop [, step ] L, dtype ])

The start, stop and step attribute provide the values for starting value, stopping valueand
step value for a numerical range. Start and step values are optional. When only stop value is
given, the numerical range is generated from zero to stop value with step 1.
The dtype specifies the datatype for the NumPy array.
Consider the following statements: Stop value
Start vale Step value
In [73]: arr5 np.arange(7)
In [77]: arr6 = np.arange (1,7, 2, np.floats2)
In [74]: arr5
Out [74]: array( [0, 1, 2, 3, 4, 5, 6]) In [78]: arr6
Out[78]: array([1., 3., 5.], dtype=float32)
In
arr5.dtype
[75]:
Out[75]: dtype("int32')
(i) Creating arrays with a numerical range using linspace(). Sometimes, you neeu c
enly
spaced elements between two given limits. For this purpose, NumPy provides Imsp
be
function to which you provide, the start value, the end value and number of elements
generated for the ndarray. The syntax for using linspace() function is:
rated>)
arrayname> =
numpy. linspace(<start>, <stop>, <number of values to be genei
2 to 3
For example, following code will create an ndarray with 6 values falling in the rattg
Arri np.linspace(2, 3, 6)
Chgpter 8: DAIA VISUALIZAIICON USING PYPIOT
291
Consider some more examples:

Start value Stop value


No. of elements
In [25]: ai = np.linspace(2.5, 5, 6)
Ndarray with 6 values falling
in range 2.5 to 5
In [26]: a1
Out[ 26]: array( [2.5, 3., 3.5, 4. , 4.5, 5. 1J
In [27]: a2 = np.linspace (2.5, 5, 8)

Ndarray with 8 values falling


In [28]: a2
in range 2.5 to 5
Out[28]:
array([2.5 2.85714286, 3.21428571, 3.57142857,
4.28571429, 4.64285714, 5. 3.92857143

Some useful NumPy functions


We are giving some
NumPy functions (without much details) that may prove useful while
plotting data.

Trigonometric functions
sin(x, /[, out]) Trigonometric sine, element-wise.
cos(x, /[, out]) Cosine element-wise.
tan(x, /[. out]) Compute tangent element-wise.
arcsin(x, /[, out]1) inverse sine, element-wise.
arccos(x, /[. out]) Trigonometric inverse cosine, element-wise.

arctan(x, /, out ]) Trigonometricinverse tangent, element-wise.


Hyperbolic functions
sinh(x, /[ out]) Hyperbolic sine, element-wise.
cosh(x, /[ out]) Hyperbolic cosine, element-wise.
tanh(x, /[. out]) Compute hyperbolic tangent element-wise.
arcsinh (x, /[, out]) Inverse hyperbolic sine element-wise.
arccosh(x, /[, out]) Inverse hyperbolic cosine, element-wise.
arctanh(x, /[, out]) Inverse hyperbolic tangent element-wise.
Rounding Functions
round_(a[, decimals, out]) Round an array to the given number of decimals.

floor(x, /[. out]) Return the floor of the input, element-wise.


ceil(x, /L, out]) Return the ceiling of the input, element-wise.
trunc (x, /[, out]) Return the truncated value of the input, element-wise.
EXponents and logarithms
exp(x, /[. out]) Calculate the exponential of all elements in the input array.

exp2(x, /[, out]) Calculate 2*p for all p in the input array
Log(x, /[, out]) Natural logarithm, element-wise.
log10(x, /[, out]) Return the base 10 logarithm f the input array, element-wise.
log2 (x, /[, out]) Base-2 logarithm of x.

Loglp(x, /[, out) Return the natural logarithm of one


plus the nput arrav, element-wise.
COMPUTER SCIENCE WITH PYTHON
292 XIL

Parameters used in the above functions:

X array_like sequence

out 1array, None, or tuple of ndarray and None, optional argumen


it is a location into which the result is stored. If provided, it must have a sthape that tihe mputs broadcast

to. If not provided or None, a freshly-allocated array is returned.

bee below how useful the numpy functions are while plotting. Although you shall learn about
all components of plotting in the coming section, yet following code lines make you appreciate
the use of numpy arrays and functions. (Don't worry if things are not clear right now, they will

be, soon. I promise)


In [39]: import numpy as np

In 40]: import matplotlib.pyplot as pl

Generate an arruy in runge 1..5.


In [41]: x = np.linspace (1,5, 6)
huving 6 elements

In [42]: y np.log(x)

In [43]: pl.plot(x,y)
Out[43]: [<matplotlib.lines. Line2D at 8x8ef79d8>]
6

12

10 1

08

06

04

02

00

10 15 20 25 30 35
40 4550

8.2.2B Basics of Simple Plotting


Data visualization essentially means
graphical representation of compiled data. Thus, grapns
and charts are very effective tools for data visualization. You
can create many different types
graphs and charts using PyPlot but we shall stick to just a few of them as per your
syllabus
Some commonly used chart types are
Line Chart. A line chart or line graph is a type of chart which displays
series of data points called 'markers' connected by straight line intormato asa
Bar Chart. A bar chart
segments.
or bar graph is a chart or graph that presents with

rectangular bars with heights or lengths proportional to the values that they ie categoricalu epresent.

The bars can be plotted or vertically horizontally.


Pie Chart. A pie
chart (or a
circle chart) is a circular divided

into slices to illustrate numerical


statistical graphic, wu
proportion.
DATA VISUALIZATION USING PYPLOT 293
Chapter 8
:

Some commonly used chart types are shown in figure below.

100

075 1
050 1

025 1 5

000

0 25

-050
)5
-075

-100 00
10 Ban Del Hyd Mum

Aline chart or line graph is a type of chart which A bar chart is a chart that presents categorical data

displays information as a series of data points called with rectangular bars with heights proportional to the

'markers' connected by straight line segments. values that they represent.

Vidya
Kshama
A pie chart (or a
16.71% 32.2996
circle chart) is a
circular statistical
New
graphic, which is
divided into slices to m 24 22%
26.5

illustratenumerical Namrta Karuna


proportion

Figure 8.2 Some commonly used chart types.

Following section talks about how you can create various chart types using pyplot methods.

8.3 CREATING CHARTS WITH MATPLOTLIB LIBRARY'S PYPLOT INTERFACE

You know that graphs and charts play a big and an important role in data visualization and
decision making, Every chart type has a different utility and serves a different purpose.
Let us talk about how you can create line, bar and pre charts using matplotlib.pyplot library of

Python.
As stated earlier make sure to import matplotlib.pyplot library interface and other reauired
1ibraries before you start using any of their functions.

8.3.1 Line Chart


A line chart or line graph is a type of chart which displays LINE CHART
rOrmation as a series of data points called markers' Aline chart or line graph is a type
Connected line
segments. The PyPlot interface of chart which displays information
by straight as a series of data points called
Orrers plot() function for creatingaline graph. Caretully
80 through the example codes given below to understand 'markers connected by straight
line segments.
the
working of plot().
cOMPUTER SCIENCE WITH PYTHONX
294
three lists, namely a, b and c
Say we have following
a = [1, 2, 3, 4]
list
of values in
a
double
b containing values
as
-List
b [2, 4, 6, 8]
values in list a

List c containing
values squares of
C =[1, 4, 9, 16]
list a vS values of
list b, then, in simnlacs
Now, it you want to plot a line chart for all values of
form you may write:
statement 1s to be given just once
The import
import matplotlib.pyplot as pl
pl.plot(a, b)
NOTE
And python will show you result as:
Data points are called
markers
In [28]: pl.plot(a, b)
[<matplotlib. lines. Line2D at 8xd277e38>]
Out[28:

The values of list b


are plotted on
vertical axis The values of list a are
plotted on horizontal axis
10 15 20 25 30 35

But are you satisfied with the result? Shouldn't the axes show
the labels of the axes? Let us say we want to label the x-axis, the NOTE
horizontal axis, as 'Some values' and the y-axis, the vertical axis Before using any PyPlot
as 'Doubled values'. You can set x-axis' and y-axis' labels using function or numpy
functions xlabel() and ylabel() respectively, i.e.,: function, make sure that
these libraries are

imported beforehand.
<matplotlib.pyplot or its alias> .xlabel (<str>)
and

<matplotlib.pyplot or its alias>.ylabel (<str>)


So you may write (since we used identifier pl as alias for matplotlib.pyplot m
statement) :

pl.xlabel("Some Values ")


pl.ylabel("Doubled Values")
pl.plot(a, b)
Let what
us see,
Python does.
298 COMPUTER SCIENCE WITH PYTHONYu

You can control the type of marker i.e.,, dots or crosses or diamonds etc. by specitying desired
marker type from the table below. If you do not specify marker type, then data points will not
be marked specifically on the line chart and its default type will be same as that ofthe line type.
Also, the markersize is to be specified in points and markeredgecolor must be a valid color

able 8.3 Marker Types for Plotting


marker
description marker description marker description
point marker Square marker 3 tri_left marker
pentagon marker 41 tri_right marker
PIxel marker p
circle marker star marker v triangle_down marker
CA
plus marker h hexagonl marker triangle_upmarker
hexagon2 marker triangle_left marker
x X marker HP
D diamond marker 1 tri_down marker triangle_rightmarker
d thin_diamond marker 2 tri_up marker vline, hline markers
Now consider following example where p = [1, 2, 3, 4 and q = [2, 4, 6, 8

n 61: plt.plot(p, q, k', marker='d', markersize = 5, markeredgecolor red")


Out[61]: [<matplotlib.lines . Line2D at 0xd09c310>]

/Line color is black (color'k')


Marker type = smal diamond ('d')

Marker size =5 points


Marker color = 'red'

15 20 25 0 35 40

Note you can combine the marker type with color code, eg., 'T+ when given for line color marks
these:
the color as 'red' and markertype as plus(+). Consider two following examples combining
Here marker color
Line colorand markerstyle combined separately specified
so marker takes same color as line

linestyle solid') In [76]: plt.plot(P, 9, Linestyle 5olid,


In [75]: plt.plot(P, 9,
Out[75]: matplotlib. lings.Line2D at exbdfc470>] markeredgecolor="
Out[76]: [<matplotlib. linej. Line2D at 0xbd46c50>J

15 20 25 30
10
40
10 15 20 25 30 35
COMPUTER SCIENCE WITH PYTHON
296 XI

commands in script(py extension) is often a Preters


a
writing plotting
But the tirst method of
<matplotlib.pyplo>.show) command in the o to
choice tor many. Also, in a script, u s e
show a plot as per given specitications.
Color in a Line Chart
8.3.1A Changing Line Style, Line Width and Line
in line chart, you can control the look of
the plotted line by specifvino
its
While plotting a

features like
Line width, Line color, line style
Line marker tyype, size

etc.
specify the color code next to
the data being plotting in plot
To change line color, you can
function as shown below:
<color code>)
matplotlib> .plot (<data1>, [, data2],
You can use color codes as: 'r' for red, 'y' for vellow, 'g tor green, "b for blue etc. (Complete

color codes list has been given in Table 8.2), eg

import matplotlib. pyplot as pltt


import numpy as np

X = np.arange (0., 10, 0.1)


a = np.cos (x)

b = np.sin(x)
Color code blue for ndarray a
plt.plot (x, a, 'b')
Color code ed for ndarray b
plt.plot(x, b, 'r')
plt.show()
The output produced by above script is as shown below

100

075

050

025

000

-0 25
50

-0 75
-1 00 NOT
2 4 6 10 color
Even if you skip the
information in plot(
Please note that even if you skip the Python will plot
multiple
color information in plot(), with
Python will plot multiple lines in the same plot with different lines in the same plot
but these
colors but these colors are decided different colors
internally by Python. colors are
decided

internally by Python.
fer8DATA VISUALIZATION USING PYPLOT
297
Table 8.2 Dijfferent Color Codes

character color character color character color


blue
'm magenta Cyan
'g 8reen
yellow W white
red k' black
In addition, you can also
specify colors in many other
ways, including full color names
'red', 'green etc.), hex
strings ('#008000') etc. (e8
To change Line
width, you can give
additional argument in plot( as
100

linewidth <width> where you have to


=
4 pts linewidth
50
specify the width value in
points, e.g, 025

00
#x, a, bare same as
earlier code -0 25
plt.plot(x, a, linewidth = 2) -050
plt.plot (x, b, linewidth = 4) -0.75
2 pts linewidth
-1.00
The result produced by above code is as
shown here :
To change the line style, you can add following additional optional argument in plot( ) function:
linestyle or ls [ 'solid'| dashed', dashdot, dotted']
=

e.g
#X, a, b are same as earlier code Possible line styles are: 'solid'
plt.plot(x, a, linewidth = 2)
for solid line, 'dashed' for
dashed line, 'dotted' for dotted
plt.plot(x, b, linewidth =4, linestyle = 'dashed') line nd
'dashdot for
dashdotted line.
The result produced by above code is as shown here:
100 Linestyle =*'
075 linestyle= dashed"
050
025 Linestyle =''
000
-25
Linestyle ='
-50
15
-1 00 Linestyle ''
10

8.3.1B Changir Marker Type, Size and Color


Recall that data points being plotted are called nmarkers. lo change marker type, its size and color

you can give following additional optional arguments in plot()function:


marker = <valid marker type> , markersize = <1n points>, markeredgecolor - eusls al

2 0.75 points, 2.0 points etc.


Wlath or thickness is measured in points e.g.,
298 COMPUTER SCIENCE WITH
PYTHON XII

You can control the type of marker i.e., dos or crosses or damonds etc. by sSpecilying desire.
marker type from the table below. If vou do not specify marker type, then data points will
not
be marked specitically on the line chart and its default type will be same as that of the linetype
Also, the markersize is to be specified in points and markeredgecolor must be a valid color

able 8.3 Marker Types for Plotting

marker
marker description marker description description
point marker square marker 3 tri left marker

pIxel marker p pentagon marker 4 tri_right marker


circle marker star marker triangle_down marker
A
plus marker h hexagonl marker triangle_up marker
x x marker H hexagon2 marker triangle_left marker
D diamond marker 1' tri_down marker triangle_right marker
d thin_diamond marker 2 tri_up marker ' , '_vline, hline markers
Now consider following example where p = [1, 2, 3, 4] andq= [2, 4, 6, 8]

n 6 1 : plt.plot (p, q,k,marker= d , markersize = 5, markeredgecolor =

Out 61]: [<matplotlib. lines.Line20D at 0xd09c310>]

Line color is black (color'k')


Marker type = small diamond ('d')

Marker size = 5 points

Marker color = 'red'

10 15 20 25 30 35 40

Note you can combine the marker type with color code, eg., 't' when given for line color marks
the color as 'red' and markertype as plus(+"). Consider two following examples combining these:

Line color and marker style combined Here marker color


so marker takes same color as line separately specified

In
In [75]: plt.plot(p, 9, ,linestyle solid') [76]: plt.plot(p, 4, 1inestyle
Out 75]: [<matplotlib.lines.Line2D at 0xbdfc470>] markeredgecolor="b)
Out[76]: [ <matplotlib. lines. Line2D at 8xbd46c58>
8

15 20 25 30 35
40
15 20 5 30 5
298 COMPUTER SCIENCE WITH PYTHON
- XI

1ou can control the type of marker i.e., dots or crosses or dianmoinas etc. by specifying desino
marker type from the table below. If you do not specify marker type, then data points will
not
be marked specifically on the line chart and its default type will be same as that of the line tyno
pe
Also, the markersize is to be specified in points and markeredgecolor must be a valid color

able 8.3 Marker Types for Plotting

marker description marker description marker


description
square marker 3 tri_left marker
point marker s'
pixel marker pentagon marker 4 tri_right marker
p
o Circle marker star marker v triangle_down marker
CA

plus marker h' hexagonl marker triangle_up marker


x X marker H hexagon2 marker triangle_left marker
D diamond marker tri_down marker triangle_Iight marker
d thin_diamond marker 2 tri_up marker , vline, hline markers
Now consider following example where p = [1, 2, 3, 4] and q = [2, 4, 6, 81

In 61: plt.plot(p, q, k, marken= d, markersize = 5, markeredgecolor =red)


Out[61]: [ <matplotlib. lines.Line2D at 8xd09c310>]

Line color is black (color'k')


Marker type =small diamond ('d')
Marker size =5 points
Marker color = 'red

10 15 20 25 30 35 40

Note you can combine the marker type with color code, e.g, 'r+' when given for line colormarks
the color as 'red' and markertype as plus(+). Consider two following examples combiningthese

|Line color and marker style combined Here marker color


so marker takes same color as line
separately specified

In [75]: plt.plot(P, 9, linestyle 'solid") In [76]: plt.plot(p, 9, linestyle solid ,


Out [ 75): matplotlib.lings. Line2D at exbdfc470»]
markeredgecolor=
Out 76]: (<matplotlib.line. Line2D at 8xbd46c58% j

15 20 25 30 5 40

10 15 20 25 30 35 40
Chopter 8 : ATA VISUALIZATION USIN PYPLOT
299
See, when you do not specity markeredgecolor separately in
color as the line. Also, it
you do not specify the
plot(), the marker takes the samne
linestyle separately along with linecolor- and-
marketstyle-conmbinati0H-string (e.g., 'rt above), Python will only plot the markers and not the
line, (see below). To get the line, specify linestyle argument also as shown above.
In [3]: plt.plot(p,9, 'no")
Out[3]:[<matplotlib.lines.Line2D at 0x8834770>]

if you do not specify the


linestyle argument separately
along with linecolor-&-
marketstyle-string (e.g.. 'rt or
'bo' etc.), Python will only plot
the markers and not the line

20 25 30 35 40

So full useful syntax of plot(O can be summarized as:


plot( <data1> [, <data2>] [, <colorcode and marker type>] [, <linewidth>]
..

L, <linestyle>] [, <marker>] [, <markersize>] [,


<markeredgecolor>])
where,
data1, data2
sequences of values to be plotted on X-axis and y-axis respectively
are

Rest of the arguments affect the look and format of the line chart as given below
color code with markertype color and marker symbol for the line chart
linewidth width of the line in points (a float value)
linestyle can be ['solid' | 'dashed', 'dashdot, 'dotted' or take markertype string|
marker a symbol denoting valid marker style such a s , 'o', *, '*, 'd', and others
etc.

markersize size of marker in points (a float value)


markeredgecolor color for markers; should be a valid color identified by PVPlot

please note that this is still not the complete and full syntax of plott )
Complete syntax coverage of plot() is beyond the scope of the book.

NOTE
If vou are working on a Jupyter Notebook, you can make the plots appear inline
Example 8.1 Create an array in in the notebook by using following magic function :
the %amatplotlib inline
range 1 to 20 with values 1.25
If vou don't use above function, the plots will appear in a pop up window
part. Another array contains the as with
other methods.
Og values of the elements in first
array.
vs second in a line chart.
4)Simply plot the two arrays first
(6) In the plot of first s second arvay, specify the iNS (Cotanng first array's values) title a
Random Values' and y-axis title as "Logarithm Values'.
300 COMPUTER SCIENCE WITH PYTHON

(c) Create a third array that stores the COS zalues offirst array and then plot both Hhe second and
tiird arvays os first array. The Cos values should be plotted with a dashdotted line.

(i) Change the marker type as a circle with blue color in second array.
(e) Only mark the data points as this : second array data points as blue small diamonds, third
arvray data points as black circles.
Note Show commands and their results.

Solution.
import numpy as np In [16]: print(a)
2.25 3.5 4.75 6. 7.25 8.5 9.75 11. 12.25 13.5
I 1. 14.75
Import matplotlib.pyplot as plt 16. 17.25 18.5 19.751
a
np.arange(1, 20, 1.25)
=
In [17]: print(b)
0.81093022 1.25276297 1.55814462 1.79175947 1.98180147
[0.
b np.log(a) 2.14006616 2.27726729 2.39789527 2.50552594 2.68268969 2.69124308
2.77258872 2.84781214 2.91777073 2.98315349]

(a) plt.plot (a, b)

In [18]: plt.plot (a, b)


Out[18]: [<matplotlib.linea20 at 0xca@e938> 1
0

25

20

15

10

05

00
50 75 10 0 12 5 15.0 17.5 200

(b) In 19]: plt.plot(a, b)


plt.plot(a, b) plt.xlabel( Random Values' )
plt.ylabel( Loganithm Values)
plt.xlabel ('Random Values') .
****
plt.show()
plt.ylabe.l ("Logarithm Values')
plt.show()

05 1

50P5T n5150 175 20


******ia nununun
andom alue
Chapter 8: DAIA VISUALIZAIION USING PYPLOT

In [30]: pl.xlabel(' Some values)


295
Out [30]: Text(8.5,0, 'Some values')

See, on IPython console's


prompt, the three
statements have produced
06 1 three charts, even if you
wanted a single chart

02

00 No axes titles because Python has not


0 02
8 10
Somevalues considered any of the previous statements

In [31]:
pl.ylabel( Squared values ") In [32]: pl.plot(a,b)
Out [31: Text(0,0.5, Squared values")
10T Out[32]: [<matplotlib. lines Line20 at 0xd42b390>
.

81

2 04 08 15 20 25 30 40
No X-axis title only Y-axis title as
only
current statement is considered

See, Python has shown us three ditferent charts, one for each statement we
what issued. But this is not
we wanted. We wanted all these three statemernts to take effect in a
single plot.
On the if you give these three statements, Python
prompt, interactively draws
statement separately. To apply plot for each
multiple
statements on a single plot, do one of the following:
1) Either write a script, store it with py extension and then run it

(11) Or, on the IPython console


In [33]: pl.xlabel( Some values')Press CTRL-ENTER here
pl.ylabel( Doubled Values')
prompt, press CTRL + ENTERR
... pl.plot(a, b)
to end each statement and Press ENTER in the end
ENTER in the end. This wil Out [33]: [<matplotlib .lines. Line20 at
8xd464678 ]
group multiple statements and
execute them as one unit, i.e,

Now all these statements have

impacted one plot as you can see


the labels on both X and Y axes and
graph plotted in the same plot

10 15 30
Seme values
Chopter8 : DAIA VISUALIZAIION USING PYPLOT
301
()
C np.cos(a)
In [21]: c =np.cos (a)
plt.plot(a, b)
plt.plot(a,b) plt.plot (a, c, linestyle- dashdot
plt.show()
plt.plot (a, C, linestyle ="dashdot")
plt.show()
30

* mua m unsmuneurena nu sun*ar


25

00
-05

25 50 75 10.0 125 150 175


200

(d) In [22]: c = np.cos(a)


C np.cos (a) plt.plot(a, b)
plt.plot(a, C, bo, linestyle= dashdot')
plt.plot(a, b) plt.show()
plt.plot(a, c, 'bo', linestyle ="dashdot')
plt.show() 30

To see
these graphs
*Bsesueu* a eanan oun 25

20

action

-05

-10
Scan
25 50 75 10.0
OR Code 125 15 0 175 20 0

In [23]: c np.cos (a)


e)
C np.cos (a)
plt.plot(a, b, "bd')
plt.plot(a, C,ro")
plt.show()
plt.plot(a, b, bd*)
plt.plot (a, C, 'ro) .
plt.show()
unsen susansun sn su
**Ra***as, us a ndensi sna.b
30

20
5
0

-05

5
50 5 100 12 5 15 0 175
200

You might also like