Unit-III-Matplotlib
Unit-III-Matplotlib
UNIT-3
Matplotlib
© Vivekananda School of Information Technology, VIPS, Delhi-34, by Dr. Deepali Kamthania U3.1
Learning Objective
• Installation
• Simple plot
• Markers
• Lines
• Gridlines
• Subplot
• Legend function
• Creating scatterplot (CMAP and Colorbar), Barplot, Stacked bar chart, Grouped
barchart, pie chart, histogram
Installation
• Matplotlib library
Main use is to plot the graphs, in order to visualize the
data
IDE already installed
import matplotlib (no error as already installed)
IDLE
import matplotlib (need to install explicitly)
Open command prompt(cmd)
cd path of python installation
pip install matplotlib
• Anaconda
Anaconda prompt
Conda list
© Vivekananda School of Information Technology, VIPS, Delhi-34, by Dr. Deepali Kamthania U3.3
Vivekananda School of Information Technology, VIPS, Delhi-34 , by Dr. Deepali Kamthania U3.1
BCA-212 Introduction to Data Science
Introduction
• Matplotlib (Math chart library) is a data visualization
package.
• Two Modules
pyplot
Pylab
• Types of plots
Line chart
Bar chart
Histogram
Scatter plot
Pie plot/chart
© Vivekananda School of Information Technology, VIPS, Delhi-34, by Dr. Deepali Kamthania U3.4
Description
• Figure: Outline
• Axes: place where chart is drawn (x, y and z axis)
• Legend: use functionality of line
• Marker: different style, size and color
Figure
Z axis
© Vivekananda School of Information Technology, VIPS, Delhi-34, by Dr. Deepali Kamthania U3.5
Parts of a Figure
© Vivekananda School of Information Technology, VIPS, Delhi-34, by Dr. Deepali Kamthania U3.6
Vivekananda School of Information Technology, VIPS, Delhi-34 , by Dr. Deepali Kamthania U3.2
BCA-212 Introduction to Data Science
Cont…
from matplotlib import pyplot as plt
# import matpltlib.pyplot as plt
x=[1,2,3,4,5]
y=[10,20,30,40,50]
plt.plot(x,y)
plt.title("Simple line plot")
plt.xlabel("x-axis")
plt.ylabel("y-axis")
plt.show()
© Vivekananda School of Information Technology, VIPS, Delhi-34, by Dr. Deepali Kamthania U3.8
Markers
• Markers
Representation of a point in a graph/chart
• Markers can be of different styles
plot(x, y, marker” “)
• Styes
O circle
S square
o Diamond
P Pentagon
h hexagon
. Point
* star
+ plus
| vertical line
-horizontal line
© Vivekananda School of Information Technology, VIPS, Delhi-34, by Dr. Deepali Kamthania U3.9
Vivekananda School of Information Technology, VIPS, Delhi-34 , by Dr. Deepali Kamthania U3.3
BCA-212 Introduction to Data Science
Marker (Color)
• Color
Two type of marker color
Edge color (mec-marker edge color)
Face color (mfc-marker face color)
Represented as a single character
• Color as character of hexadecimal format
#RGB
R (00 to FF), G (00 to FF), B (00 to FF)
#123456
R-12
G-34
B-56
© Vivekananda School of Information Technology, VIPS, Delhi-34, by Dr. Deepali Kamthania U3.10
Marker (Size)
• Size of marker
ms=“ “
plot(x, y, marker=“ “, mec =“ “, mfc=“ “, ms=“ “)
© Vivekananda School of Information Technology, VIPS, Delhi-34, by Dr. Deepali Kamthania U3.11
Cont…
from matplotlib import pyplot as plt
# import matpltlib.pyplot as plt
import numpy as np
x=np.arange(0,10,2)
y=x**2
plt.plot(x,y,marker="d",ms=15,mec="r",mfc="y")
#plt.plot(x,y,marker="o",ms=10,mec="c",mfc="w")
#plt.plot(x,y,marker="o",ms=10,mec="#00aabb",mfc="#ffffff")
plt.title("Simple line plot")
plt.xlabel("x-axis")
plt.ylabel("y-axis")
plt.show()
© Vivekananda School of Information Technology, VIPS, Delhi-34, by Dr. Deepali Kamthania U3.12
Vivekananda School of Information Technology, VIPS, Delhi-34 , by Dr. Deepali Kamthania U3.4
BCA-212 Introduction to Data Science
Line
• Line styles ls
solid
dotted
dashed
dasheddot
none (line won’t appear)
• Line width lw
• Line color C
© Vivekananda School of Information Technology, VIPS, Delhi-34, by Dr. Deepali Kamthania U3.13
Cont…
from matplotlib import pyplot as plt
import numpy as np
x=np.arange(0,10,2)
y=x**2
print(x,y)
#plt.plot(x,y)
#plt.plot(x,y,ls="dashdot",lw="3",c="r")
plt.plot(x,y,marker=".",ls="none",lw="3",c="r")
plt.show()
© Vivekananda School of Information Technology, VIPS, Delhi-34, by Dr. Deepali Kamthania U3.14
Font Properties
• Font properties on title and labels
Font dictionary (fontdict) need to be defined as key value
pair in curly bracket
f1={'family':'arial','color':'red','size':15}
f2={'family':'calibri','color':'green','size':15}
plt.title(“Sample Plot",fontdict=f1)
plt.xlabel("x-value",fontdict=f2)
plt.ylabel("y-value",fontdict=f2)
© Vivekananda School of Information Technology, VIPS, Delhi-34, by Dr. Deepali Kamthania U3.15
Vivekananda School of Information Technology, VIPS, Delhi-34 , by Dr. Deepali Kamthania U3.5
BCA-212 Introduction to Data Science
Cont…
from matplotlib import pyplot as plt
import numpy as np
x=np.arange(0,10,2)
y=x*10
plt.plot(x,y)
f1={'family':'arial','color':'red','size':15}
f2={'family':'calibri','color':'green','size':15}
plt.title("Multiple of 10",fontdict=f1)
plt.xlabel("x-value",fontdict=f2)
plt.ylabel("y-value",fontdict=f2)
plt.show()
© Vivekananda School of Information Technology, VIPS, Delhi-34, by Dr. Deepali Kamthania U3.16
Gridlines
• Grid function with line properties
grid() get lines on chart
grid(axis=“x”)
axis=x, y or both (default)
plt.grid(axis="both",ls="dotted",lw=1,c="red")
© Vivekananda School of Information Technology, VIPS, Delhi-34, by Dr. Deepali Kamthania U3.17
Subplot
• Multiple plots in same figure
• subplot function have three arguments
• subplot (R, C, I)
R row
C column
Iindex of plot
• Supertitle
suptitle( )
© Vivekananda School of Information Technology, VIPS, Delhi-34, by Dr. Deepali Kamthania U3.18
Vivekananda School of Information Technology, VIPS, Delhi-34 , by Dr. Deepali Kamthania U3.6
BCA-212 Introduction to Data Science
Legend
• Legend function
Define functionality of line, if we draw multiple line in a plot
It will create a box
• Two methods
• legends( ) without parameters
If legend() then use label plot( )
plt.plot(x,y, label=“square”)
plt.legend( )
• legends( parameters)
Pass as string
plt.legend(loc="upper right", framealpha=0,
facecolor="yellow", edgecolor="black", fancybox=True,
shadow=True, fontsize=10)
© Vivekananda School of Information Technology, VIPS, Delhi-34, by Dr. Deepali Kamthania U3.19
Parameters
• location (loc) as number or string
loc= 0 to 10
“upper left”, “upper right”,”lower left”, “center”, “lower
center” etc.
• framealpha= 0 to 1
Give transparency of frame
• facecolor=“red” or #RGB
Area inside box
• edgecolor=“red” or #RGB
• Shadow=True/False
• Fancybox= True/False
Rectangle or rounded rectangle
© Vivekananda School of Information Technology, VIPS, Delhi-34, by Dr. Deepali Kamthania U3.20
Scatter Plot
• Creating Scatter plot
• scatter( )
• scatter(x, y, color=“red” or #RGB, marker=”o”,
S=15, linewidth=10,slpha=0.5)
© Vivekananda School of Information Technology, VIPS, Delhi-34, by Dr. Deepali Kamthania U3.21
Vivekananda School of Information Technology, VIPS, Delhi-34 , by Dr. Deepali Kamthania U3.7
BCA-212 Introduction to Data Science
© Vivekananda School of Information Technology, VIPS, Delhi-34, by Dr. Deepali Kamthania U3.22
Cont…
from matplotlib import x=[10,20,30,40,50]
pyplot as plt y=[200,300,100,500,400]
x=[10,20,30,40,50] colors=[10,40,60,80,70]
y=[200,300,100,500,400] OR size=[100,50,200,250,150]
colors=["red","green","blue #plt.scatter(x,y,c=colors,s=
","yellow","black"] size,cmap="viridis")
size=[100,50,200,250,150] plt.scatter(x,y,c=colors,s=si
plt.scatter(x,y,c=colors,s=s ze,cmap="Accent")
ize) plt.colorbar()
plt.show() plt.show()
© Vivekananda School of Information Technology, VIPS, Delhi-34, by Dr. Deepali Kamthania U3.23
Barplot
• Barplot(Horizontal and Vertical)
Barchart represents category of data with rectangular bar
width, length and height that is proportional to the value.
Simple bar, Plot, Bar(), BarH( )
• There are two functions
Bar()
Represent bar vertically
BarH()
Represent bar in horizontal manner
© Vivekananda School of Information Technology, VIPS, Delhi-34, by Dr. Deepali Kamthania U3.24
Vivekananda School of Information Technology, VIPS, Delhi-34 , by Dr. Deepali Kamthania U3.8
BCA-212 Introduction to Data Science
Cont…
from matplotlib import pyplot as plt
x=['A','B',’C','D']
y=[10,30,20,40]
#plt.bar(x,y)
#plt.bar(x,y,color='red',width=1) #Default width 0.8
plt.barh(x,y,color='red',height=0.8)
plt.show()
OR
Bars of different color
c=["red","green","blue","black"]
plt.bar(x,y,color=c,width=0.2) or plt.barh(x,y,color=c,heigth=0.2)
plt.show()
© Vivekananda School of Information Technology, VIPS, Delhi-34, by Dr. Deepali Kamthania U3.25
© Vivekananda School of Information Technology, VIPS, Delhi-34, by Dr. Deepali Kamthania U3.26
© Vivekananda School of Information Technology, VIPS, Delhi-34, by Dr. Deepali Kamthania U3.27
Vivekananda School of Information Technology, VIPS, Delhi-34 , by Dr. Deepali Kamthania U3.9
BCA-212 Introduction to Data Science
Pie Chart
• Pie chart/ pie graph /pie plot
Circular statistical graph for charts which is divided into
different slices based upon given division and each slice
we call as wedge
Parameters
plt.pie(student_values,labels=student_performance,startangle=0,
explode=[0.2,0.1,0.3,0.1],shadow=True,colors=["black","blue","yel
low","red"],autopct="%2.1f%%")
startangle,
where it should represent x axis default value =0, and move counter
clock wise. To change use startangle=90 or 180
Explode
to extract some portion from circle
Shadow=false (default)
Autopct
to give percentage % %
© Vivekananda School of Information Technology, VIPS, Delhi-34, by Dr. Deepali Kamthania U3.28
Pie Chart
• DEMO
© Vivekananda School of Information Technology, VIPS, Delhi-34, by Dr. Deepali Kamthania U3.29
Histogram
• Histogram
Is an accurate representation of the historic data
(numerical data divided into equal intervals and how many
values fall in that interval)
plt.hist(marks,grade_interval,histtype="bar")
defaultrwidth=1
plt.hist(marks,grade_interval,histtype="bar",rwidth=0.7,fac
ecolor="blue")
plt.hist(marks,grade_interval,histtype="step")
plt.hist(marks,grade_interval,histtype="stepfilled")
For step and stepfilled histogram rwidth not required
DEMO
© Vivekananda School of Information Technology, VIPS, Delhi-34, by Dr. Deepali Kamthania U3.30
Vivekananda School of Information Technology, VIPS, Delhi-34 , by Dr. Deepali Kamthania U3.10
BCA-212 Introduction to Data Science
Scatter Plot
• Scatter plot
Is used to represent a pair of numerical data one with x
axis and y axis and each representation will be with the
help of a dot
plt,scatter (x, y,color=“black”)
plt.scatter(x1,y1,c=color,s=size,alpha=0.5,cmap="viridis")
plt.colorbar()
© Vivekananda School of Information Technology, VIPS, Delhi-34, by Dr. Deepali Kamthania U3.31
© Vivekananda School of Information Technology, VIPS, Delhi-34, by Dr. Deepali Kamthania U3.32
Data Analysis
• Dataset for analysis
© Vivekananda School of Information Technology, VIPS, Delhi-34, by Dr. Deepali Kamthania U3.33
Vivekananda School of Information Technology, VIPS, Delhi-34 , by Dr. Deepali Kamthania U3.11