Exploring Pylab in
Python with examples
Sarvajanik College of Engineering & Technology
Computer (Shift-1) 8th Semester Group 3 (Morning)
Prepared by:
Name Enrollment No
Dhameyia Vatsalkumar Nareshbhai 140420107012
Shah Dhrashti Paramal 140420107013
Dudhwala Francy Kalpesh 140420107014
Dumasia Yazad Dumasia 140420107015
Prof. Niriali Nanavati
Prof. Rachana Oza
Guided
by
2
Content: A glimpse of what is to come
• Introduction to Pylab
• Introduction to Matplotlib
• Few basic libraries along with Matplotlib
• How to install matplotlib in our computer
• Formatting the Plot
• Few type of basic Plot
• Reference
3
PyLab is actually embedded inside Matplotlib and provides
a Matlab like experience for the user.
It imports portions of Matplotlib and NumPy. Many
examples on the web use it as a simpler MATLAB like
experience, but it is not recommended anymore as it
doesn't nurture understanding of Python itself, thus leaving
you in a limited environment.
Introduction to Pylab
4
Pylab is a module that belongs to the python mathematics library
matplotlib.
Pylab is one kind of “magic function” that can call within ipython or
interactive python. By invoking it, python interpreter will import
matplotlib and numpy modules for accessing their built-in functions.
Pylab combines the numerical module numpy with the graphical
plotting module pyplot.
Pylab was designed with the interactive python interpreter in mind, and
therefore many of its functions are short and require minimal typing.
Introduction to Pylab
5
 Matplotlib is a library for making 2D plots of arrays in Python. Although it
has its origins in emulating the MATLAB graphics commands, it is
independent of MATLAB, and can be used in a Pythonic, object oriented
way.
 Although Matplotlib is written primarily in pure Python, it makes heavy use
of NumPy and other extension code to provide good performance even for
large arrays.
 Matplotlib is designed with the philosophy that you should be able to create
simple plots with just a few commands, or just one! If you want to see a
histogram of your data, you shouldn’t need to instantiate objects, call
methods, set properties, and so on; it should just work.
Introduction to Matplotlib
6
7
Few basic libraries along with Matplotlib
NumPy:
► NumPy, the Numerical Python package, forms much of the underlying numerical
foundation that everything else here relies on.
► Or in other words, it is a library for the Python programming language, adding
support for large, multi-dimensional arrays and matrices, along with a large
collection of high-level mathematical functions to operate on these arrays.
►For use this library , import NumPy as np
► E.g. import numpy as np
print np.log2(8)
returns 3, as 23=8 . For this form, log2(3) will return an error, as log2 is
unknown to Python without the np.
► Or else this would like
from numpy import *
log2(8)
► which returns 3. However, np.log2(3) will no longer work but it not preferable as by
coder.
88
Pyplot:
 Matplotlib is a plotting library for the Python programming language and
its numerical mathematics extension NumPy. It provides an object-
oriented API for embedding plots into applications using general-
purpose GUI toolkits like Tkinter.
 Example of Pyplot :
Few basic libraries along with Matplotlib
import matplotlib.pyplot as plt
plt.plot([1, 2, 3, 4])
plt.ylabel('some numbers on Y-axis’)
plt.xlabel('some numbers on X-axis’)
plt.show()
9
How to install matplotlib in windows 10
Setting Path for Python 2.7.13 in windows in order download of matplotlib:
Necessary path
required for in
order download
matplotlib
10
Install matplotlib via command prompt in windows:
Setp2. Install of matplotlib via CMD
Step 1. In order install package in
python we have update your package
manager
11
How to install matplotlib in Ubuntu Linux
 Step 1:Open up a bash shell.
 Step 2:Type in the following command to download and install Matplotlib:
sudo apt-get install python-matplotlib
 Step 3:Type in the administrators password to proceed with the install.
How to install matplotlib in CentOS Linux
►Step 1:Open up a terminal.
►Step 2:Type in the following command to download and install
Matplotlib:
sudo yum install python-matplotlib
►Step 3:It will proceed to the install from internet.
12
Changing the Color of line and style of line:
It is very useful to plot more than one set of data on same axes
and to differentiate between them by using different line &
marker styles and colors .
plylab.plot(X,Y,par)
You can specify the color by inserting 3rd parameter into the
plot() method.
Matplotlib offers a variety of options for color, linestyle and
marker.
Formatting the Plot
13
Color
code
Color
Displayed
r Red
b Blue
g Green
c Cyan
m Magenta
y Yellow
k Black
w White
Marker
code
Marker
Displayed
+ Plus Sign
. Dot
O Circle
* Star
p Pentagon
s Square
x X Character
D Diamond
h Hexagon
^ Triangle
Line style
code
Line Style
Displayed
- Solid Line
-- Dashed
Line
: Dotted
Line
-. Dash-
Dotted
line
None No
Connectin
g Lines
Formatting codes
14
 It is very important to always label the axis of plots to tell the user or viewer
what they are looking at which variable as X- axis and Y-axis.
 Command use in for label in python:
pl.xlabel(‘X-axis variable’)
pl.ylabel(‘Y-axis variable’)
 Your can add title for your plot by using python command :
pl.title(‘Put your title’)
 You can save output of your plot as image:
plt.savefig(“output.png")
 You can also change the x and y range displayed on your plot:
pl.xlim(x_low,x_high)
pl.ylim(y_low,y_high)
Plot and Axis titles and limits
15
1. Line Plot
2. Scatter Plot
3. Histograms Plot
4. Pie Chart
5. Subplot
Few type of basic Plot:
16
Line Plot:
A line plot is used to relate the value of x to particular value y
import numpy as nmp
import pylab as pyl
x=[1,2,3,4,5]
y=[1,8,5,55,66]
pyl.plot(x,y,linestyle="-.",marker="o",color="red")
pyl.title("Line Plot Demo")
pyl.xlabel("X-axis")
pyl.ylabel("Y-axis")
pyl.savefig("line_demo.png")
pyl.show()
import numpy as np
import matplotlib.pyplot as plt
fig, (ax1) = plt.subplots(1)
x = np.linspace(0, 1, 10)
for j in range(10):
ax1.plot(x, x * j)
plt.savefig("one_many.png")
plt.show()
17
Scatter Plot :
A Scatter plot is used the position of each element is scattered.
import numpy as nmp
import pylab as pyl
x=nmp.random.randn(1,100)
y=nmp.random.randn(1,100)
pyl.title("Scatter Plot Demon")
pyl.scatter(x,y,s=20,color="red")
#s denote size of dot
pyl.savefig("scatter_demo.png")
pyl.show()
import numpy as np
import matplotlib.pyplot as plt
x = [0,2,4,6,8,10]
y = [0]*len(x)
s = [20*2**n for n in range(len(x))]
plt.scatter(x,y,s=s,color="green")
plt.savefig("radom_plot_dots.png")
plt.show()
18
Pie chart Plot :
 A pie graph (or pie chart) is a specialized graph used in statistics. The independent variable
is plotted around a circle in either a clockwise direction or a counterclockwise direction. The
dependent variable (usually a percentage) is rendered as an arc whose measure is
proportional to the magnitude of the quantity. The independent variable can attain a finite
number of discrete values. The dependent variable can attain any value from zero to 100
percent.
import matplotlib.pyplot as pyplot
x_list = [10, 12, 50]
label_list = ["Python", "Artificial Intelligence",
"Project"]
pyplot.axis("equal")
pyplot.pie(x_list,labels=label_list,autopct="%1.0f%%")
#autopct show the percentage of each element
pyplot.title("Subject of Final Semester")
pyplot.savefig("pie_demo.png")
pyplot.show()
19
Explode Pie chart Plot :
import numpy as nmp
import pylab as ptl
labels = ["Python", "Artificial Intelligence", "Project"]
sizes=[13,16,70]
colors=["gold","yellowgreen","lightblue"]
explode = (0.1,0.1,0.1)
ptl.axis("equal")
ptl.pie(sizes,explode=explode,labels=labels,colors=
colors,autopct="%1.1f%%",shadow=True,startangle
=110)
ptl.legend(labels,loc="upper left")
ptl.title("Subject of Final Semester")
ptl.savefig("pie_explode_demo.png")
ptl.show()
20
Subplot :
subplot(m,n,p) divides the
current figure into an m-by-n
grid and creates axes in the
position specified by p. The
first subplot is the first column
of the first row, the second
subplot is the second column of
the first row, and so on. If axes
exist in the specified position,
then this command makes the
axes the current axes.
21
Subplot :
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(0)
dt = 0.01
Fs = 1/dt
t = np.arange(0, 10, dt)
nse = np.random.randn(len(t))
r = np.exp(-t/0.05)
cnse = np.convolve(nse, r)*dt
cnse = cnse[:len(t)]
s = 0.1*np.sin(2*np.pi*t) + cnse
plt.subplot(3, 2, 1)
plt.plot(t, s)
plt.title(' Simple demo of spectrum
anaylsis’)
plt.ylabel('Frequency'+'n')
#plt.savefig("spr1.png")
plt.subplot(3, 2, 3)
plt.magnitude_spectrum(s, Fs=Fs)
plt.xlabel('Energy')
plt.ylabel('Frequency'+'n')
#plt.savefig("spr2.png")
plt.subplot(3, 2, 4)
plt.magnitude_spectrum(s, Fs=Fs,
scale='dB')
plt.xlabel('Energy')
plt.ylabel(' ')
#plt.savefig("spr3.png")
plt.subplot(3, 2, 5)
plt.angle_spectrum(s, Fs=Fs)
plt.xlabel('Energy')
plt.ylabel('Frequency'+'n')
#plt.savefig("sp4.png")
plt.subplot(3, 2, 6)
plt.phase_spectrum(s, Fs=Fs)
plt.xlabel('Energy')
plt.ylabel(' ')
plt.savefig("spr_demo.png")
plt.show()
22
23
Reference
https://matplotlib.org
24
Thank You…

Introduction to Pylab and Matploitlib.

  • 1.
    Exploring Pylab in Pythonwith examples Sarvajanik College of Engineering & Technology Computer (Shift-1) 8th Semester Group 3 (Morning)
  • 2.
    Prepared by: Name EnrollmentNo Dhameyia Vatsalkumar Nareshbhai 140420107012 Shah Dhrashti Paramal 140420107013 Dudhwala Francy Kalpesh 140420107014 Dumasia Yazad Dumasia 140420107015 Prof. Niriali Nanavati Prof. Rachana Oza Guided by 2
  • 3.
    Content: A glimpseof what is to come • Introduction to Pylab • Introduction to Matplotlib • Few basic libraries along with Matplotlib • How to install matplotlib in our computer • Formatting the Plot • Few type of basic Plot • Reference 3
  • 4.
    PyLab is actuallyembedded inside Matplotlib and provides a Matlab like experience for the user. It imports portions of Matplotlib and NumPy. Many examples on the web use it as a simpler MATLAB like experience, but it is not recommended anymore as it doesn't nurture understanding of Python itself, thus leaving you in a limited environment. Introduction to Pylab 4
  • 5.
    Pylab is amodule that belongs to the python mathematics library matplotlib. Pylab is one kind of “magic function” that can call within ipython or interactive python. By invoking it, python interpreter will import matplotlib and numpy modules for accessing their built-in functions. Pylab combines the numerical module numpy with the graphical plotting module pyplot. Pylab was designed with the interactive python interpreter in mind, and therefore many of its functions are short and require minimal typing. Introduction to Pylab 5
  • 6.
     Matplotlib isa library for making 2D plots of arrays in Python. Although it has its origins in emulating the MATLAB graphics commands, it is independent of MATLAB, and can be used in a Pythonic, object oriented way.  Although Matplotlib is written primarily in pure Python, it makes heavy use of NumPy and other extension code to provide good performance even for large arrays.  Matplotlib is designed with the philosophy that you should be able to create simple plots with just a few commands, or just one! If you want to see a histogram of your data, you shouldn’t need to instantiate objects, call methods, set properties, and so on; it should just work. Introduction to Matplotlib 6
  • 7.
    7 Few basic librariesalong with Matplotlib NumPy: ► NumPy, the Numerical Python package, forms much of the underlying numerical foundation that everything else here relies on. ► Or in other words, it is a library for the Python programming language, adding support for large, multi-dimensional arrays and matrices, along with a large collection of high-level mathematical functions to operate on these arrays. ►For use this library , import NumPy as np ► E.g. import numpy as np print np.log2(8) returns 3, as 23=8 . For this form, log2(3) will return an error, as log2 is unknown to Python without the np. ► Or else this would like from numpy import * log2(8) ► which returns 3. However, np.log2(3) will no longer work but it not preferable as by coder.
  • 8.
    88 Pyplot:  Matplotlib isa plotting library for the Python programming language and its numerical mathematics extension NumPy. It provides an object- oriented API for embedding plots into applications using general- purpose GUI toolkits like Tkinter.  Example of Pyplot : Few basic libraries along with Matplotlib import matplotlib.pyplot as plt plt.plot([1, 2, 3, 4]) plt.ylabel('some numbers on Y-axis’) plt.xlabel('some numbers on X-axis’) plt.show()
  • 9.
    9 How to installmatplotlib in windows 10 Setting Path for Python 2.7.13 in windows in order download of matplotlib: Necessary path required for in order download matplotlib
  • 10.
    10 Install matplotlib viacommand prompt in windows: Setp2. Install of matplotlib via CMD Step 1. In order install package in python we have update your package manager
  • 11.
    11 How to installmatplotlib in Ubuntu Linux  Step 1:Open up a bash shell.  Step 2:Type in the following command to download and install Matplotlib: sudo apt-get install python-matplotlib  Step 3:Type in the administrators password to proceed with the install. How to install matplotlib in CentOS Linux ►Step 1:Open up a terminal. ►Step 2:Type in the following command to download and install Matplotlib: sudo yum install python-matplotlib ►Step 3:It will proceed to the install from internet.
  • 12.
    12 Changing the Colorof line and style of line: It is very useful to plot more than one set of data on same axes and to differentiate between them by using different line & marker styles and colors . plylab.plot(X,Y,par) You can specify the color by inserting 3rd parameter into the plot() method. Matplotlib offers a variety of options for color, linestyle and marker. Formatting the Plot
  • 13.
    13 Color code Color Displayed r Red b Blue gGreen c Cyan m Magenta y Yellow k Black w White Marker code Marker Displayed + Plus Sign . Dot O Circle * Star p Pentagon s Square x X Character D Diamond h Hexagon ^ Triangle Line style code Line Style Displayed - Solid Line -- Dashed Line : Dotted Line -. Dash- Dotted line None No Connectin g Lines Formatting codes
  • 14.
    14  It isvery important to always label the axis of plots to tell the user or viewer what they are looking at which variable as X- axis and Y-axis.  Command use in for label in python: pl.xlabel(‘X-axis variable’) pl.ylabel(‘Y-axis variable’)  Your can add title for your plot by using python command : pl.title(‘Put your title’)  You can save output of your plot as image: plt.savefig(“output.png")  You can also change the x and y range displayed on your plot: pl.xlim(x_low,x_high) pl.ylim(y_low,y_high) Plot and Axis titles and limits
  • 15.
    15 1. Line Plot 2.Scatter Plot 3. Histograms Plot 4. Pie Chart 5. Subplot Few type of basic Plot:
  • 16.
    16 Line Plot: A lineplot is used to relate the value of x to particular value y import numpy as nmp import pylab as pyl x=[1,2,3,4,5] y=[1,8,5,55,66] pyl.plot(x,y,linestyle="-.",marker="o",color="red") pyl.title("Line Plot Demo") pyl.xlabel("X-axis") pyl.ylabel("Y-axis") pyl.savefig("line_demo.png") pyl.show() import numpy as np import matplotlib.pyplot as plt fig, (ax1) = plt.subplots(1) x = np.linspace(0, 1, 10) for j in range(10): ax1.plot(x, x * j) plt.savefig("one_many.png") plt.show()
  • 17.
    17 Scatter Plot : AScatter plot is used the position of each element is scattered. import numpy as nmp import pylab as pyl x=nmp.random.randn(1,100) y=nmp.random.randn(1,100) pyl.title("Scatter Plot Demon") pyl.scatter(x,y,s=20,color="red") #s denote size of dot pyl.savefig("scatter_demo.png") pyl.show() import numpy as np import matplotlib.pyplot as plt x = [0,2,4,6,8,10] y = [0]*len(x) s = [20*2**n for n in range(len(x))] plt.scatter(x,y,s=s,color="green") plt.savefig("radom_plot_dots.png") plt.show()
  • 18.
    18 Pie chart Plot:  A pie graph (or pie chart) is a specialized graph used in statistics. The independent variable is plotted around a circle in either a clockwise direction or a counterclockwise direction. The dependent variable (usually a percentage) is rendered as an arc whose measure is proportional to the magnitude of the quantity. The independent variable can attain a finite number of discrete values. The dependent variable can attain any value from zero to 100 percent. import matplotlib.pyplot as pyplot x_list = [10, 12, 50] label_list = ["Python", "Artificial Intelligence", "Project"] pyplot.axis("equal") pyplot.pie(x_list,labels=label_list,autopct="%1.0f%%") #autopct show the percentage of each element pyplot.title("Subject of Final Semester") pyplot.savefig("pie_demo.png") pyplot.show()
  • 19.
    19 Explode Pie chartPlot : import numpy as nmp import pylab as ptl labels = ["Python", "Artificial Intelligence", "Project"] sizes=[13,16,70] colors=["gold","yellowgreen","lightblue"] explode = (0.1,0.1,0.1) ptl.axis("equal") ptl.pie(sizes,explode=explode,labels=labels,colors= colors,autopct="%1.1f%%",shadow=True,startangle =110) ptl.legend(labels,loc="upper left") ptl.title("Subject of Final Semester") ptl.savefig("pie_explode_demo.png") ptl.show()
  • 20.
    20 Subplot : subplot(m,n,p) dividesthe current figure into an m-by-n grid and creates axes in the position specified by p. The first subplot is the first column of the first row, the second subplot is the second column of the first row, and so on. If axes exist in the specified position, then this command makes the axes the current axes.
  • 21.
    21 Subplot : import matplotlib.pyplotas plt import numpy as np np.random.seed(0) dt = 0.01 Fs = 1/dt t = np.arange(0, 10, dt) nse = np.random.randn(len(t)) r = np.exp(-t/0.05) cnse = np.convolve(nse, r)*dt cnse = cnse[:len(t)] s = 0.1*np.sin(2*np.pi*t) + cnse plt.subplot(3, 2, 1) plt.plot(t, s) plt.title(' Simple demo of spectrum anaylsis’) plt.ylabel('Frequency'+'n') #plt.savefig("spr1.png") plt.subplot(3, 2, 3) plt.magnitude_spectrum(s, Fs=Fs) plt.xlabel('Energy') plt.ylabel('Frequency'+'n') #plt.savefig("spr2.png") plt.subplot(3, 2, 4) plt.magnitude_spectrum(s, Fs=Fs, scale='dB') plt.xlabel('Energy') plt.ylabel(' ') #plt.savefig("spr3.png") plt.subplot(3, 2, 5) plt.angle_spectrum(s, Fs=Fs) plt.xlabel('Energy') plt.ylabel('Frequency'+'n') #plt.savefig("sp4.png") plt.subplot(3, 2, 6) plt.phase_spectrum(s, Fs=Fs) plt.xlabel('Energy') plt.ylabel(' ') plt.savefig("spr_demo.png") plt.show()
  • 22.
  • 23.
  • 24.