0% found this document useful (0 votes)
14 views16 pages

Matplotlib Data Visualization Guide

The document provides an overview of Matplotlib, a Python library used for data visualization through various types of plots such as line plots, bar charts, histograms, and pie charts. It includes installation instructions, basic usage examples, and code snippets demonstrating how to create different visualizations. The document also covers additional features like adding titles, labels, legends, and customizing plot styles.

Uploaded by

shashank13072003
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)
14 views16 pages

Matplotlib Data Visualization Guide

The document provides an overview of Matplotlib, a Python library used for data visualization through various types of plots such as line plots, bar charts, histograms, and pie charts. It includes installation instructions, basic usage examples, and code snippets demonstrating how to create different visualizations. The document also covers additional features like adding titles, labels, legends, and customizing plot styles.

Uploaded by

shashank13072003
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

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 [Link] as plt [Link] 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]
[Link](x,y)#plot is a function used to draw
#a 2-D plot or graph using values on x-axis and y-axis
[Link]() # 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]
[Link](x,y,color='green')# color parameter is used to color the plot
[Link]()

In [5]: #Adding title to the plot and label to the axis.


x=[1,2,3]
y=[2,4,1]
#adding label to axis
[Link]("X-Axis")
[Link]("Y-Axis")
#adding Title to the plot
[Link]("This is my First Plot")
[Link](x,y)#plot is a function used to draw
#a 2-D plot or graph using values on x-axis and y-axis
[Link]() # 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]
[Link]("X-Axis")
[Link]("Y-Axis")
[Link]("Multiple Graph")
[Link](x,y,color='red')
x1=[3,5,6]
y1=[4,3,2]
[Link](x1,y1,color='green')
[Link]()#it will display multiple graph

In [7]: #Displaying legend in the plot


x=[1,2,3]
y=[2,4,1]
[Link]("X-Axis")
[Link]("Y-Axis")
[Link]("Multiple Graph with legend")
[Link](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]
[Link](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
[Link](loc=3)#legend function is used to display legends in the graph
#loc value will decide the place where legend will be displayed
[Link]()

In [8]: #Displaying legend in the plot


x=[1,2,3]
y=[2,4,1]
[Link]("X-Axis")
[Link]("Y-Axis")
[Link]("Multiple Graph with legend")
#'-' solid line(default)
#'--' dashed line
#'-.' dashed dot line
#':' dotted line
[Link](x,y,color='red',linestyle='--',label='line-1')
x1=[3,5,6]
y1=[4,3,2]
[Link](x1,y1,color='green',linestyle='-.',label='line-2')
[Link](loc=3)
[Link]()

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
[Link](x,y,linewidth=2)#to linewidth is used to decide the width of ploted line
[Link]()

In [10]: #highlighting corners of a plot using marker parameter


x=[1,8,3,13,6,5]
y=[2,4,21,12,3,5]
[Link]("X-Axis")
[Link]("Y-Axis")
[Link]("Graph with corner marking")
[Link](x,y,color='red',marker='o',markersize=10,markerfacecolor='green')
[Link]()

In [11]: #plotting a velocity graph by using v=u+a*t


#calculation
u=20
a=5
t=[Link](2,21)
v=[]
for i in t:
[Link](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


[Link](t,v)
[Link]('Time')
[Link]('Velocity')
[Link]('Velocity and time graph')
[Link]()

In [18]: #plotting the graph


[Link](t,v)
[Link](5,15)# is used to clip(limit) the x axis
[Link](40,100)#is used to clip(limit) the y axis
[Link]('Time')
[Link]('Velocity')
[Link]('Velocity and time graph')
[Link]()
[Link]()

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('[Link]')
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]: [Link](data['Age'],data['Sales'])#it is a function of matplotlib


[Link]('Age')
[Link]('Sales')
[Link]()#it creates grids corresponding to the x and y axis
[Link]()

In [19]: [Link]()#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
[Link](age,inter,range,color='green')
[Link]('Age')
[Link]('No. of persons')
[Link]('Age distribution plot')
[Link]()

In [24]: [Link]()#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

[Link](revenue,labels=item,wedgeprops={'edgecolor':'black'},autopct='%1.1f%%')
[Link]('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']
[Link](revenue,labels=item,wedgeprops={'edgecolor':'black'},autopct='%1.1f%%',startan
[Link]('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']
[Link](revenue,labels=item,wedgeprops={'edgecolor':'black'},explode=ex,
autopct='%1.1f%%',startangle=180)
[Link]('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']
[Link](revenue,labels=item,wedgeprops={'edgecolor':'black'},explode=ex,
shadow=True,autopct='%1.1f%%',startangle=180)
[Link]('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]
[Link](months,sales_car,sales_bike,labels=['car','bike'])
[Link]()
[Link]("car vs bike sale")
[Link]()

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]: [Link](data['Age'],data['Income'])
[Link]()

In [38]: [Link](data['Age'],data['Income'],color='red',marker='*',s=200)
[Link]()

In [43]: #ploting curves of given equation:


x=[Link](0,2*([Link]),0.1)#[Link] 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=[Link](x)
[Link](x,y)
[Link]()
y=[Link](x)
[Link](x,y)
[Link]()
y=[Link](x)
[Link](x,y)
[Link]()

In [46]: #any mathematical curve can be ploted


x=[Link](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
[Link](x,y)
[Link]()

In [55]: #Creating your figure:


#figure() function is used to create a figure of your own plots
fig=[Link](figsize=(6,6),dpi=100,facecolor='white')
acts=['eat','sleep','work','play']
time=[3,7,8,6]
color=['r','y','b','g']
[Link](time,labels=acts,colors=color,startangle=90,
explode=[0,0,0.1,0.2],shadow=True,autopct='%1.1f%%')
[Link](loc=3)
#[Link]()#do not show the plot in case of saving it as figure
[Link](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=[Link](0,2*[Link],40)
y=[Link](x**2)
fig,ax=[Link]()# it returns two values one is figure and other
#is axis(one or more) in the form of numpy array
[Link](x,y)
[Link]()

In [71]: fig,ax=[Link](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
[Link](r'C:\Users\Admin\Desktop\my_fig2.pdf')
# return fig is saved in memory

In [72]: fig,ax=[Link](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)
[Link]()
#[Link](r'C:\Users\Admin\Desktop\my_fig2.pdf')

In [73]: fig,ax=[Link](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)
[Link]()
#[Link](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

Common questions

Powered by AI

Legends in Matplotlib plots are used to label different data series, helping viewers identify what each graph or plot represents in multi-line plots. The placement of legends can be adjusted using the 'loc' parameter in the plt.legend() function, where different numeric and string values determine the position (e.g., loc=3 places it in the lower left).

Matplotlib is a library used for data visualization in the form of charts, graphs, and maps. It operates on 2-D numpy arrays and allows users to create various types of graphs such as line plots, scatter plots, bar charts, histograms, pie charts, and stacked plots, among others. For creating these plots, it provides functionalities for styling, such as coloring, adding titles and labels, including legends, and setting axis limits .

Markers in Matplotlib can be customized to highlight specific data points through parameters such as 'marker', 'markersize', and 'markerfacecolor'. This allows points to be visually distinct, drawing attention or differentiating them on a plot. Such customization is valuable for emphasizing key data points without altering the overall plot complexity .

The pyplot interface in Matplotlib is crucial as it provides a MATLAB-like interface for plotting, simplifying the process of creating and configuring plots. It offers several features such as functions to plot graphs, manage axis labels and titles, customize plot styles with colours, line styles, markers, and more. Pyplot also allows for the combination of multiple graphs into a single plot and facilitates the inclusion of legends, making it easier to present information clearly and effectively .

Matplotlib supports plotting mathematical functions by using numpy to define a range of x-values and calculating corresponding y-values. For example, trigonometric functions like sine, cosine, and tangent can be visualized by employing np.sin(x), np.cos(x), and np.tan(x) with x-values generated by numpy's np.arange() or np.linspace(), and then plotting these with plt.plot().

Labeling with plt.xlabel() and plt.ylabel() functions, alongside titles via plt.title(), significantly enhances the readability of plots by providing context for the data axes and the plot content. Coloring is controlled through parameters like 'color', which distinguishes different data sets or highlights specific plot elements, aiding in visual separation and easier interpretation of complex data in a multi-plot setup .

Matplotlib allows multiple graphs in a single plot by calling plt.plot() multiple times before displaying with plt.show(). Different graphs can be styled individually using parameters like 'color', 'linestyle', and 'label' which define distinct visual characteristics for each line. Legends can then be used to distinguish between these differently styled graphs .

Pie charts in Matplotlib are used to show percentage representation of different parts of a whole. The pie() function creates pie charts and can include exploded slices using the 'explode' parameter to highlight particular sections. Shadow effects are added using 'shadow=True', which adds depth to the chart, enhancing visual appeal and comprehension of the data's relative proportions .

The plt.subplots() function is utilized for creating layout variations of multiple plots by specifying the number of rows and columns of subplots. This function returns a Figure and an array of Axes objects, which can be indexed to individually plot data on each subplot. Various configurations, such as vertical, horizontal, or matrix layouts, are achievable by adjusting parameters like (3,1), (1,3), or (2,2), respectively, enabling organized and comparative visual displays of data .

Grid settings, enabled through plt.grid(), improve graph clarity by adding reference lines that facilitate the visual alignment of data points with axis scales. Axis limiting, using plt.xlim() and plt.ylim(), focuses the viewer’s attention on specific data ranges and prevents outliers from skewing visual interpretation. These settings collectively enhance data comprehension and the precision of the conveyed information .

You might also like