0% found this document useful (0 votes)
60 views17 pages

17 Plotting With Pyplot

Matplotlib's Pyplot is a commonly used interface for data visualization in Python. It provides many functions for creating line charts, scatter plots, bar charts, pie charts, and more. Some key functions include plot() for line and scatter plots, bar() for bar charts, and pie() for pie charts. Pyplot allows customizing visual properties like colors, markers, line widths, and adding labels/legends. It is a versatile package for plotting and exploring data visually in Python.

Uploaded by

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

17 Plotting With Pyplot

Matplotlib's Pyplot is a commonly used interface for data visualization in Python. It provides many functions for creating line charts, scatter plots, bar charts, pie charts, and more. Some key functions include plot() for line and scatter plots, bar() for bar charts, and pie() for pie charts. Pyplot allows customizing visual properties like colors, markers, line widths, and adding labels/legends. It is a versatile package for plotting and exploring data visually in Python.

Uploaded by

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

PLOTTING WITH PYPLOT

DATA VISUALIZATION: Graphical or visual representation of information and data using


visual elements like charts, graphs, and maps etc. is data visualization. It is normally useful
in decision-making.
For data visualization in Python, the Matplotlib library’s Pyplot interface is used.
ABOUT MATPLOTLIB
1. The Matplotlib is a Python library that provides many interfaces and functionality for
2d graphics similar to MATLAB (high performance language for technical computing)
in various forms.
2. High quality plotting library of Python.
3. It provides a quick way to visualize data from Python and publication quality figures
in many formats.
4. It offers many different named collections of methods, One such method /interface
is PyPlot
BASICS OF SIMPLE PLOTTING

LINE CHART: It is a type of chart which displays information as a series of data points
called markers connected by straight line segments.With PyPlot, a line chart is
created using plot() function.
Example of Line chart program
import matplotlib.pyplot as pl
a=[1,2,3,4,5,6]
b=[1,4,9,16,25,36]
pl.plot(a,b)

To label x-axis, the horizontal axis,as ‘Values’ and the y axis, the vertical axis as
‘Squared values’. We can set x-axis and y-axis labels using functions xlabel() and ylabel()
respectively. We can write the same as
import matplotlib.pyplot as pl
a=[1,2,3,4,5,6]
b=[1,4,9,16,25,36]
pl.xlabel(‘values’)
pl.ylabel(‘Squared values’)
pl.plot(a,b)
The output produced by the above Python program is given below

SPECIFYING PLOT SIZE AND GRID


figure(): This function is used to give figure size
For example, figure(figsize=(10,5)) means 10 units wide(x coordinate) & 5 units long( y
coordinates). If we want to show the grid on the plot, we can use grid() function.
import matplotlib.pyplot as pl
a=[1,2,3,4,5,6]
b=[1,4,9,16,25,36]
pl.xlabel(‘values’)
pl.ylabel(‘Squared values’)
pl.figure(figsize=(10,15))
pl.grid(True)
pl.plot(a,b)

The plot() function allows us specity multiple settings for our chart/graph such as
1. Color (line color/marker color)
2. Marker size
3. Marker type
CHANGING LINE COLOR AND STYLE
LINE COLOR:
We can use color codes as :’r’ for red,’y’ for yellow, ‘g’ for green,’b’ for blue etc.
import matplotlib.pyplot as pl
a=[1,2,3,4,5,6]
b=[1,4,9,16,25,36]
pl.xlabel(‘values’)
pl.ylabel(‘Squared values’)
pl.figure(figsize(10,5))
pl,grid(True)
pl.plot(a,b,’r’)
LINE WIDTH: linewidth=<width>,
Linewidth = 2.5 where width value is given in points
import matplotlib.pyplot as pl
a=[1,2,3,4,5,6]
b=[1,4,9,16,25,36]
pl.xlabel("values")
pl.ylabel("Squared values")
pl.figure(figsize=(10,10))
pl.grid(False)
pl.plot(a,b,'r', linewidth=7.5)
LINE STYLE: linestyle or is =[ solid| dashed, dashdot,dotted
import matplotlib.pyplot as pl
a=[1,2,3,4,5,6]
b=[1,4,9,16,25,36]
pl.xlabel("values")
pl.ylabel("Squared values")
pl.figure(figsize=(10,10))
pl.grid(False)
pl.plot(a,b,'g', linestyle=”dotted”, linewidth=7.5)
import matplotlib.pyplot as pl
import numpy as np
x= np.arange(0,10,.1)
a= np.sin(x)
b= np.cos(x)
pl.plot(x,a,"b")
pl.plot(x,b,"r")
pl.show()
CHANGING MARKER TYPE, SIZE AND COLOR

marker=<valid marker type>,markersize=<in points>,markeredgecolor=<valid color>


import matplotlib.pyplot as pl
a=[1,2,3,4,5,6]
b=[1,4,9,16,25,36]
pl.xlabel("values")
pl.ylabel("Squared values")
pl.figure(figsize=(10,10))
pl.grid(False)
pl.plot(a,b,'r', marker='d', markersize=5,markeredgecolor="blue")

MARKER DESCRIPTION MARKER DESCRIPTION MARKER DESCRIPTION


‘.’ Point marker ‘D’ diamond
‘,’ pixel ‘d’ Thin-diamond
‘o’ circle ‘s’ square
‘+’ Plus ‘p’ Pentagon
‘x’ x ‘*’ star

import matplotlib.pyplot as pl
a=[1,2,3,4,5,6]
b=[1,4,9,16,25,36]
pl.xlabel("values")
pl.ylabel("Squared values")
pl.figure(figsize=(10,15))
pl.grid(False)
pl.plot(a,b,'rD', markersize=5,markeredgecolor="blue")

CREATING SCATTER CHARTS


Scatter charts can be created through
i. Plot() function- marker type specified plot() function with out linestyle argument
creates the scatter chart
ii. Scatter() function
SCATTER CHARTS USING PLOT() FUNCTION
import matplotlib.pyplot as pl
a=[1,2,3,4,5,6]
b=[1,4,9,16,25,36]
pl.xlabel("values")
pl.ylabel("Squared values")
pl.figure(figsize=(10,15))
pl.grid(False)
pl.plot(a,b,'rD', markersize=5,markeredgecolor="blue")
SCATTER CHARTS USING SCATTER() FUNCTION
The syntax of scatter function is
Matplotlib.pyplot.scatter(x,y,s= None,c=None,marker=None)
Where x,y – data position
S – The marker size in points
C= marker color, sequence
Marker - MarkerStyle
import matplotlib.pyplot as pl
x=[1,2,3,4,5]
a=[2,4,6,8,10]
pl.scatter(x,a,marker="*",c="b",s=20)
pl.show()
Even though both plot() and scatter() functions are used to create scatter charts,
scatter function can be used to change the properties of each individual point like size,
face color, edge color etc.
EXAMPLE TO SHOW THE ABOVE CONCEPT
import matplotlib.pyplot as pl
x=[1,2,3,4,5]
a=[2,4,6,8,10]
col=['r','b','y','g','m']
size=[10,20,30,40,50]
pl.scatter(x,a,marker="*",c=col,s=size)
pl.show()

CREATING BAR CHARTS AND PIE CHARTS


import matplotlib.pyplot as pl
Class=["I","II","III","IV","V"]
strength=[198,204,215,230,250]
pl.xlabel("CLASS")
pl.ylabel("STRENGTH")
pl.figure(figsize=(5,5))
pl.grid(False)
pl.bar(Class, strength)
S
T
R
E
N
G
T
H

CLASS
The order of the bars plotted may be different from the order in actual data sequence
import matplotlib.pyplot as pl
Class=["I","II","III","IV","V"]
girls=[98,104,55,95,103]
boys=[44,86,98,90,97]
pl.figure(figsize=(5,5))
pl.grid(False)
pl.bar(Class, girls)
pl.bar(Class, boys)
pl.xlabel("CLASS")
pl.ylabel("GIRLS, BOYS STRENGTH")
import matplotlib.pyplot as pl
Class=["I","II","III","IV","V"]
strength=[198,204,215,230,250]
girls=[98,104,55,95,103]
boys=[44,86,98,90,97]
pl.figure(figsize=(5,5))
pl.grid(False)
pl.bar(Class, strength)
pl.bar(Class, girls)
pl.bar(Class, boys)
pl.xlabel("CLASS")
pl.ylabel("GIRLS, BOYS STRENGTH")

CHANGING THE WIDTH OF INDIVIDUAL BAR


import matplotlib.pyplot as pl
Class=["I","II","III","IV","V"]
girls=[98,104,100,95,103]
boys=[44,86,58,90,97]
pl.figure(figsize=(5,5))
pl.grid(False)

pl.bar(girls,boys ,width=[.2,.4,1.6,.8,1.0])
pl.xlabel("CLASS")
pl.ylabel("GIRLS, BOYS STRENGTH")
import matplotlib.pyplot as pl
Class=["I","II","III","IV","V"]
girls=[98,104,100,95,103]
boys=[44,86,58,90,97]
pl.figure(figsize=(5,5))
pl.grid(False)
pl.bar(Class,boys,color=["r","b","c","k","y"])
pl.xlabel("CLASS")
pl.ylabel("BOYS STRENGTH")

In scatter() function we use c argument for color and in bar() function we use color
argument for selecting color

CREATING MULTIPLE BAR CHART


1. Decide the no. of X points. Based on this number or length, using range() or arrange()
of numpy module create a sequence
2. Decide the thickness of each bar. Accordingly adjust the size of X points on X axis.
3. Give different color to different data ranges using color argument of bar() function.
4. The width argument remains the same for all ranges
5. Plot using bar() function for each bar.

import matplotlib.pyplot as pl
import numpy as np
Class=["I","II","III","IV","V"]
girls=[98,104,100,95,103]
boys=[44,86,58,90,97]
X=np.arange(5)
pl.grid(True)
pl.bar(X+0.5,boys,color="red",width=0.25)
pl.bar(X+0.75,girls,color="blue",width=0.25)
pl.xlabel("CLASS")
pl.ylabel("BOYS STRENGTH")
NOTE: We can plot using any type of sequence (e.g. lists/ tuples/ arrays/ individual rows/
columns of dataframe as data.
CREATING HORIZONTAL BAR CHART
import matplotlib.pyplot as pl
Class=["I","II","III","IV","V"]
girls=[98,104,100,95,103]
boys=[44,86,58,90,97]
pl.figure(figsize=(5,5))
pl.grid(False)
pl.barh(Class,boys,color=["r","b","c","k","y"])
pl.xlabel("CLASS")
pl.ylabel("BOYS STRENGTH")

CREATING PIE CHARTS


Pie Chart is used to show parts to the whole and often a % share.
It is a type of graph in which a circle is divided into sectors that each represents a
proportion of the whole.
Pie() function is used to create a Pie function. It plots a single data range only. The default
shape of a pie chart is oval but you can always change to circle by using axis() by sending
“equal “ as argument to it.
import matplotlib.pyplot as pl
Class=[26,48.2,12,38]
pl.pie(Class)
import matplotlib.pyplot as pl
Marks=[95,97,92,89,98]
Subjects=['ENGLISH','SANSKRIT','MATHS','SCIENCE','SST']
pl.pie(Marks,labels=Subjects)

ADDING FORMATED SLICE PERCENTAGES TO PIE


We need to add an argument autopct with a format string, such as “%1.1F%%”

import matplotlib.pyplot as pl
Marks=[95,97,92,89,98]
Subjects=['ENGLISH','SANSKRIT','MATHS','SCIENCE','SST']
pl.pie(Marks,labels=Subjects,autopct='%1.1F%%')
“%[flags][width][.precision]type”
% -It is a special string which will determine the format of the values to be displayed
Width -total no. of characters to be displayed digits before and after decimal point + 1 for
decimal point
Flag -When 0 is specified, 0 will be preceded before the value if the value is less than
the width
Precision -no. of digits after the decimal point
Type - d or i for integer, f or F for float
%% - to print % symbol
Marks=[95,97,92,89,98]
Subjects=['ENGLISH','SANSKRIT','MATHS','SCIENCE','SST']
pl.pie(Marks,labels=Subjects,autopct='%1.1F%%')

Format string Description


“%6d” Width is 6 characters for integer data, if we give 2590 it will add 2
leading blanks to the number
“%06i” Width is 5 characters for integer data, if we give 2590 it will add 2
leading zeros to the number
“%06i %%” Width is 5 characters for integer data, if we give 2590 it will add 2
leading zeros to the number and end with %
“%06.2f” Width =6, precision=2 for float data, leading blank for padding
“%06.2f%%” Width =6, precision=2 for float data, leading blank for padding with % at
the end
import matplotlib.pyplot as pl
Marks=[95,97,92,89,98]
Subjects=['ENGLISH','SANSKRIT','MATHS','SCIENCE','SST']
pl.pie(Marks,labels=Subjects,autopct='%03d%%')

import matplotlib.pyplot as pl
Marks=[95,97,92,89,98]
Subjects=['ENGLISH','SANSKRIT','MATHS','SCIENCE','SST']
pl.pie(Marks,labels=Subjects,autopct='%3.1fd%%')

SAVING A FIGURE

You might also like