6/18/22, 9:04 AM Advanced_Python_Unit-5_Matplotlib
Matplotlib: used for data visualization. matplotlib works on 2-D numpy arrays. it is basically
used to draw or plot graphs, scatter plot,bar charts, histograms, legend title style plots. Data
visualization: it is a graphical represntation of information and data. in form of charts, maps and
graphs
for using matplotlib we must install it first using pip command
In [1]: pip install matplotlib
Requirement already satisfied: matplotlib in c:\programdata\anaconda3\lib\site-packag
es (3.3.2)
Requirement already satisfied: python-dateutil>=2.1 in c:\programdata\anaconda3\lib\s
ite-packages (from matplotlib) (2.8.1)
Requirement already satisfied: certifi>=2020.06.20 in c:\programdata\anaconda3\lib\si
te-packages (from matplotlib) (2020.6.20)
Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.3 in c:\program
data\anaconda3\lib\site-packages (from matplotlib) (2.4.7)
Requirement already satisfied: cycler>=0.10 in c:\programdata\anaconda3\lib\site-pack
ages (from matplotlib) (0.10.0)
Requirement already satisfied: pillow>=6.2.0 in c:\programdata\anaconda3\lib\site-pac
kages (from matplotlib) (8.0.1)
Requirement already satisfied: numpy>=1.15 in c:\programdata\anaconda3\lib\site-packa
ges (from matplotlib) (1.19.2)
Requirement already satisfied: kiwisolver>=1.0.1 in c:\programdata\anaconda3\lib\site
-packages (from matplotlib) (1.3.0)
Requirement already satisfied: six>=1.5 in c:\programdata\anaconda3\lib\site-packages
(from python-dateutil>=2.1->matplotlib) (1.15.0)
Note: you may need to restart the kernel to use updated packages.
we have import the library package before using it
from matplotlib import pyplot as plt import matplotlib.pyplot as plt matplotlib.pyplot is
basically an interface which is used to add style functions to the graphs craeted using matplotlib
our discussion will focus on: Line plot, mathematical plots,Scatter Plot, histograms, Bar chart, pie
chart
In [2]: from matplotlib import pyplot as plt
import numpy as np
import pandas as pd
In [ ]: #Line plot
In [3]: #plot of x vs y as line
x=[1,2,3]
y=[2,4,1]
plt.plot(x,y)#plot is a function used to draw
#a 2-D plot or graph using values on x-axis and y-axis
plt.show() # to display the last plot drwan by plot() function.
localhost:8888/nbconvert/html/Downloads/Advanced_Python_Unit-5_Matplotlib.ipynb?download=false 1/16
6/18/22, 9:04 AM Advanced_Python_Unit-5_Matplotlib
In [4]: #plot of x vs y as line
x=[1,2,3]
y=[2,4,1]
plt.plot(x,y,color='green')# color parameter is used to color the plot
plt.show()
In [5]: #Adding title to the plot and label to the axis.
x=[1,2,3]
y=[2,4,1]
#adding label to axis
plt.xlabel("X-Axis")
plt.ylabel("Y-Axis")
#adding Title to the plot
plt.title("This is my First Plot")
plt.plot(x,y)#plot is a function used to draw
#a 2-D plot or graph using values on x-axis and y-axis
plt.show() # to display the last plot drwan by plot() function.
localhost:8888/nbconvert/html/Downloads/Advanced_Python_Unit-5_Matplotlib.ipynb?download=false 2/16
6/18/22, 9:04 AM Advanced_Python_Unit-5_Matplotlib
In [6]: #Multiple graph in one plot
x=[1,2,3]
y=[2,4,1]
plt.xlabel("X-Axis")
plt.ylabel("Y-Axis")
plt.title("Multiple Graph")
plt.plot(x,y,color='red')
x1=[3,5,6]
y1=[4,3,2]
plt.plot(x1,y1,color='green')
plt.show()#it will display multiple graph
In [7]: #Displaying legend in the plot
x=[1,2,3]
y=[2,4,1]
plt.xlabel("X-Axis")
plt.ylabel("Y-Axis")
plt.title("Multiple Graph with legend")
plt.plot(x,y,color='red',label='line-1')#label parameter is used to define the
#name of plot in legend
x1=[3,5,6]
y1=[4,3,2]
plt.plot(x1,y1,color='green',label='line-2')
localhost:8888/nbconvert/html/Downloads/Advanced_Python_Unit-5_Matplotlib.ipynb?download=false 3/16
6/18/22, 9:04 AM Advanced_Python_Unit-5_Matplotlib
plt.legend(loc=3)#legend function is used to display legends in the graph
#loc value will decide the place where legend will be displayed
plt.show()
In [8]: #Displaying legend in the plot
x=[1,2,3]
y=[2,4,1]
plt.xlabel("X-Axis")
plt.ylabel("Y-Axis")
plt.title("Multiple Graph with legend")
#'-' solid line(default)
#'--' dashed line
#'-.' dashed dot line
#':' dotted line
plt.plot(x,y,color='red',linestyle='--',label='line-1')
x1=[3,5,6]
y1=[4,3,2]
plt.plot(x1,y1,color='green',linestyle='-.',label='line-2')
plt.legend(loc=3)
plt.show()
In [9]: #graph which intersects itself
x=[1,8,3,13,6,5]
y=[2,4,21,12,3,5]
localhost:8888/nbconvert/html/Downloads/Advanced_Python_Unit-5_Matplotlib.ipynb?download=false 4/16
6/18/22, 9:04 AM Advanced_Python_Unit-5_Matplotlib
plt.plot(x,y,linewidth=2)#to linewidth is used to decide the width of ploted line
plt.show()
In [10]: #highlighting corners of a plot using marker parameter
x=[1,8,3,13,6,5]
y=[2,4,21,12,3,5]
plt.xlabel("X-Axis")
plt.ylabel("Y-Axis")
plt.title("Graph with corner marking")
plt.plot(x,y,color='red',marker='o',markersize=10,markerfacecolor='green')
plt.show()
In [11]: #plotting a velocity graph by using v=u+a*t
#calculation
u=20
a=5
t=np.arange(2,21)
v=[]
for i in t:
v.append(u+a*i)
print(t)
print(v)
[ 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20]
[30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100, 105, 110, 115, 120]
localhost:8888/nbconvert/html/Downloads/Advanced_Python_Unit-5_Matplotlib.ipynb?download=false 5/16
6/18/22, 9:04 AM Advanced_Python_Unit-5_Matplotlib
In [12]: #plotting the graph
plt.plot(t,v)
plt.xlabel('Time')
plt.ylabel('Velocity')
plt.title('Velocity and time graph')
plt.show()
In [18]: #plotting the graph
plt.plot(t,v)
plt.xlim(5,15)# is used to clip(limit) the x axis
plt.ylim(40,100)#is used to clip(limit) the y axis
plt.xlabel('Time')
plt.ylabel('Velocity')
plt.title('Velocity and time graph')
plt.grid()
plt.show()
Bar Plot: it is a rectagular plot which
performs
#comparison between 2 or more identities
localhost:8888/nbconvert/html/Downloads/Advanced_Python_Unit-5_Matplotlib.ipynb?download=false 6/16
6/18/22, 9:04 AM Advanced_Python_Unit-5_Matplotlib
In [14]: data=pd.read_csv('Book.csv')
print(data)
EmpId Gender Age Sales BMI Income
0 E001 M 34 123 Normal 350
1 E002 F 40 114 Overweight 450
2 E003 F 37 135 Obesity 169
3 E004 M 30 139 Underweight 189
4 E005 F 44 117 Underweight 183
5 E006 M 36 121 Normal 80
6 E007 M 32 133 Obesity 166
7 E008 F 26 140 Normal 120
8 E009 M 32 133 Normal 75
9 E010 M 36 133 Underweight 40
In [17]: plt.bar(data['Age'],data['Sales'])#it is a function of matplotlib
plt.xlabel('Age')
plt.ylabel('Sales')
plt.grid()#it creates grids corresponding to the x and y axis
plt.show()
In [19]: data.plot.bar()#by using plot function of DF
<AxesSubplot:>
Out[19]:
Histograms: it is used for frequency distribution.
localhost:8888/nbconvert/html/Downloads/Advanced_Python_Unit-5_Matplotlib.ipynb?download=false 7/16
6/18/22, 9:04 AM Advanced_Python_Unit-5_Matplotlib
In [23]: #Histogram using matplotlib function
age=[2,5,70,40,3,55,45,50,45,43,40,44,60,7,13,57,18,11,90,77,32,21,20,40,67]
range=(0,100)
inter=10
#hist(): function to plot histogram
plt.hist(age,inter,range,color='green')
plt.xlabel('Age')
plt.ylabel('No. of persons')
plt.title('Age distribution plot')
plt.show()
In [24]: data.hist()#using hist function of DF
array([[<AxesSubplot:title={'center':'Age'}>,
Out[24]:
<AxesSubplot:title={'center':'Sales'}>],
[<AxesSubplot:title={'center':'Income'}>, <AxesSubplot:>]],
dtype=object)
pie chart or pie plot: it is used to show percentage of different partcipating entities in a whole
In [31]: #piechart: pie() function is used
revenue=[7267,6785,8765,9876,4567]
item=['veg','meat','snacks','drinks','salads']
localhost:8888/nbconvert/html/Downloads/Advanced_Python_Unit-5_Matplotlib.ipynb?download=false 8/16
6/18/22, 9:04 AM Advanced_Python_Unit-5_Matplotlib
plt.pie(revenue,labels=item,wedgeprops={'edgecolor':'black'},autopct='%1.1f%%')
plt.title('unique food court')
Text(0.5, 1.0, 'unique food court')
Out[31]:
In [32]: #piechart: pie() function is used
revenue=[7267,6785,8765,9876,4567]
item=['veg','meat','snacks','drinks','salads']
plt.pie(revenue,labels=item,wedgeprops={'edgecolor':'black'},autopct='%1.1f%%',startan
plt.title('unique food court')
Text(0.5, 1.0, 'unique food court')
Out[32]:
In [34]: #piechart: pie() function is used
revenue=[7267,6785,8765,9876,4567]
ex=[0,0,1.0,0.1,0]
item=['veg','meat','snacks','drinks','salads']
plt.pie(revenue,labels=item,wedgeprops={'edgecolor':'black'},explode=ex,
autopct='%1.1f%%',startangle=180)
plt.title('unique food court')
Text(0.5, 1.0, 'unique food court')
Out[34]:
localhost:8888/nbconvert/html/Downloads/Advanced_Python_Unit-5_Matplotlib.ipynb?download=false 9/16
6/18/22, 9:04 AM Advanced_Python_Unit-5_Matplotlib
In [35]: #piechart: pie() function is used
revenue=[7267,6785,8765,9876,4567]
ex=[0,0,1.0,0.1,0]
item=['veg','meat','snacks','drinks','salads']
plt.pie(revenue,labels=item,wedgeprops={'edgecolor':'black'},explode=ex,
shadow=True,autopct='%1.1f%%',startangle=180)
plt.title('unique food court')
Text(0.5, 1.0, 'unique food court')
Out[35]:
Stacked or Area plot: used to compare two areas of given identities.
In [36]: #stacked plot
months=['jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec']
sales_car=[120,30,56,89,90,120,34,56,78,12,45,56]
sales_bike=[240,27,34,56,98,110,150,34,10,23,72,78]
plt.stackplot(months,sales_car,sales_bike,labels=['car','bike'])
plt.legend()
plt.title("car vs bike sale")
plt.show()
localhost:8888/nbconvert/html/Downloads/Advanced_Python_Unit-5_Matplotlib.ipynb?download=false 10/16
6/18/22, 9:04 AM Advanced_Python_Unit-5_Matplotlib
In [ ]: #Scatter plot : used in machine learning for classification and clustering
In [37]: plt.scatter(data['Age'],data['Income'])
plt.show()
In [38]: plt.scatter(data['Age'],data['Income'],color='red',marker='*',s=200)
plt.show()
In [43]: #ploting curves of given equation:
x=np.arange(0,2*(np.pi),0.1)#np.pi is value pi in radian
localhost:8888/nbconvert/html/Downloads/Advanced_Python_Unit-5_Matplotlib.ipynb?download=false 11/16
6/18/22, 9:04 AM Advanced_Python_Unit-5_Matplotlib
y=np.sin(x)
plt.plot(x,y)
plt.show()
y=np.cos(x)
plt.plot(x,y)
plt.show()
y=np.tan(x)
plt.plot(x,y)
plt.show()
In [46]: #any mathematical curve can be ploted
x=np.arange(0,10,0.1)
y=x*x
localhost:8888/nbconvert/html/Downloads/Advanced_Python_Unit-5_Matplotlib.ipynb?download=false 12/16
6/18/22, 9:04 AM Advanced_Python_Unit-5_Matplotlib
plt.plot(x,y)
plt.show()
In [55]: #Creating your figure:
#figure() function is used to create a figure of your own plots
fig=plt.figure(figsize=(6,6),dpi=100,facecolor='white')
acts=['eat','sleep','work','play']
time=[3,7,8,6]
color=['r','y','b','g']
plt.pie(time,labels=acts,colors=color,startangle=90,
explode=[0,0,0.1,0.2],shadow=True,autopct='%1.1f%%')
plt.legend(loc=3)
#plt.show()#do not show the plot in case of saving it as figure
plt.savefig(r'C:\Users\Admin\Desktop\my_fig1.jpg')
#it is used to save your figure on desired location
localhost:8888/nbconvert/html/Downloads/Advanced_Python_Unit-5_Matplotlib.ipynb?download=false 13/16
6/18/22, 9:04 AM Advanced_Python_Unit-5_Matplotlib
In [69]: #subploting: dividing a plot into multiple plots
x=np.linspace(0,2*np.pi,40)
y=np.sin(x**2)
fig,ax=plt.subplots()# it returns two values one is figure and other
#is axis(one or more) in the form of numpy array
ax.plot(x,y)
plt.show()
In [71]: fig,ax=plt.subplots(3,1)#returns figure and 2d numpy array of 3x1 order
# it is used for vertical ploting of multiple plots(3x1)
ax[0].plot(x,y)
ax[1].plot(x,-y)
ax[2].plot(-x,y)
localhost:8888/nbconvert/html/Downloads/Advanced_Python_Unit-5_Matplotlib.ipynb?download=false 14/16
6/18/22, 9:04 AM Advanced_Python_Unit-5_Matplotlib
plt.savefig(r'C:\Users\Admin\Desktop\my_fig2.pdf')
# return fig is saved in memory
In [72]: fig,ax=plt.subplots(1,3)# used for Horizantal ploting of multiple plots(1x3)
ax[0].plot(x,y)
ax[1].plot(x,-y)
ax[2].plot(-x,y)
plt.show()
#plt.savefig(r'C:\Users\Admin\Desktop\my_fig2.pdf')
In [73]: fig,ax=plt.subplots(2,2)#returns figure and 2d numpy array of 2x2 order
# it is used for matrix ploting of multiple plots(2x2)
ax[0,0].plot(x,y)
ax[0,1].plot(x,-y)
ax[1,0].plot(-x,y)
ax[1,1].plot(-x,-y)
plt.show()
#plt.savefig(r'C:\Users\Admin\Desktop\my_fig2.pdf')
# return fig is saved in memory
localhost:8888/nbconvert/html/Downloads/Advanced_Python_Unit-5_Matplotlib.ipynb?download=false 15/16
6/18/22, 9:04 AM Advanced_Python_Unit-5_Matplotlib
In [ ]: #matplotlib ends
localhost:8888/nbconvert/html/Downloads/Advanced_Python_Unit-5_Matplotlib.ipynb?download=false 16/16