You are on page 1of 6

Matplotlib In Python

Niyazi ARI Prof Dr. sch. techno ETH, Makhamadsulton Ustazhanov, MsIE

Abstract-Python and one of plotting module matplotlib was 1. Python code tends to be more compact and more readable
explained briefly. Existing softwares may be enough to solve and than Matlab code.
display the results of scientific problems. But matplotlib also
2. Object-oriented prograrmn ing (OOP) in Python is simple
stepping with its Pythonic programming style to this area of
and elegant.
the software technology. The use of matplotlib is illustrated with
specific practical applications. The applied illustrations code and 3. The Python world is free and open (in several senses).
results have been suggested. 4. The Python world is open in another sense: There is a
vigorous, healthy public debate on virtually all aspects of
Index Terms-matplotlib, Python, PyLab, numpy
Python, with input from any developer or user who wants to
participate.
I. INT RODUCTION 5. There is no Matlab counterpart to Python's "import" state­
matplotlib is a Python package for Plotting that generates ment. Python's import command gives one precise control over
production quality graphs. matplotlib is designed to be able what components are used by any program.
to create simple and complex plots with a few command. 6. Python offers a wider set of choices in graphics packages
matplotlib is written to use of NumPy and other extension and toolsets.
code. With a few line of codes, it generates plots, histograms, 7. Python conforms to certain de facto standards, including
power spectra, bar charts, error charts, scatterplots etc. There zero-based indexing and the use of square brackets rather than
is a procedural "pylab" interface based on a state machine. parentheses for indexing.
matplotlib gives plots with publication quality, postscript
output for inclusion with TeX documents, embeddable in a
III. MATPLOTLIB
graphical user interface for application development.
matplotlib is open source and no license servers. matplotlib is an excellent 2D and 3D graphic plotting library

The matplotlib concept is divided in three parts: package of Python programming language, which produces

1. Pylab interface : to create plots scientific publication quality figures in a variety of hard

2. matplotlib frontend: a set of classes to lift, to create and to copy formats and interactive environments across platforms.

manage figures, text, lines, plots, etc. matplotlib is designed with the philosophy that user should be

3. matplotlib backend: Post Script Hard Copy, Vector graphics, able to create simple plots with just a few commands, or just

PNG, GTK, Tkinter, etc. one! matplotlib tries to make easy things easy and hard things

It is also possible to generate automatically PostScript files possible.

or PNG output for inclusion in dynamically generated WEB For example, using "ipython - pylab" to provide an
pages. interactive environment, to generate 10,000 gaussian random
numbers and plot a histogram with 100 bins, you simply
need to type
x randn(10000)
II. PYT HON
=

hist(x, 100)
Python is a widely used general-purpose, high-level pro­
gramming language. Its design philosophy emphasizes code
matplotlib is a multi-platform data visualization tool built
readability. Python supports multiple programming paradigms,
upon the Numpy and Scipy framework. One of matplotlibs
including object-oriented, imperative and functional program­
most important features is its ability to play well with many
ming or procedural styles. It features a dynamic type system
operating systems and graphics backends. Advantages of mat­
and automatic memory management and has a large and
plotlib:
comprehensive standard library.
1. it could be used on any operating system via its array of
In every area, specialized languages are the best choice, but
backends
Python is the second best in the area of progranuning. Python
2. it has a familiar interface: one similar to MatLab
has plus a handful of mature 3rd-party open source libraries,
3. it has a coherent vision: to do 2D graphics, and do them
namely Numpy/Scipy for numerical operations, Cython for
well
low-level optimization, IPython for interactive work, and mat­
4. it found early institutional support, from astronomers at
plotlib for plotting.
STScI and JPL
Although Python and Matlab are comparable in several
5. it has an outspoken advocate in Hunter himself, who
areas, Python offers several important advantages:
enthusiastically promoted the project within the Python world.

The Nigerian Turkish Nile University,Abuja,Nigeria


Comparison between matplotlib and MATLAB
Manuscript received April 19,2014 The pylab interface makes matplotlib easy to learn for

978-1-4799-4106-3/14/$31.00 © 2014 IEEE


2

experienced MATLAB users, making it available alternative II Figure 1 =@)

to MATLAB as a teaching tool for numerical mathematics � 0 0 +


and signal processing. Typically pylab is imported to bring
NumPy and matplotlib into a single global namespace for
the most MATLAB like syntax, however a more explicit
import style, which names both matplotlib and NumPy, is the
preferred coding style.
Some advantages from combination of Python, NumPy, and
matplotlib over MATLAB include:
1. Easy to get started
2. Great control of every element in a figure, including figure
size and DPI.
3. High-quality output in many formats, including PNG, PDF,
SVG, EPS, and PGF.
4. GUI for interactively exploring figures and support for
headless generation of figure files (useful for batch jobs). 2. Simple Plot with labels
matplotlib highly suitable for generating figures for scientific
publications is that all aspects of the figure can be controlled » > from pylab import *

programmatically. This is important for reproducibility and from numpy import *

convenient when one needs to regenerate the figure with » > def f(t):
updated data or change its appearance. f l =exp(-t)*sin(2*pi*t)
re turn f1
5. B ased on Python, a full-featured modern object-oriented
programming language suitable for large-scale software » > t l =arange(O.O, 4.0, 0.01)
» > plot(tl, f(tl »
development. [ <matplotlib.lines.Line2D object at OxOSCOFS I0> ]
6. Free, open source, no license servers. » > grid(True)
» > title( ' Expo nential Sinus')
7. Native Scalable Vector Graphics (SV G) support. <matplotlib.text.Text object at OxOSC07A90>
8. Postscript output for inclusion with TeX documents. >>> xlabel('t' )
<matplotlib.text.Text object at OxOSBFB490>
9. Embeddable in a graphical user interface for application
» > ylabel('f ( t ) ')
development. <matplotlib.text.Text object at OxOSC07SS0>
» > show()
10. Coding is easy enough that user can understand it and
extend it.

IV. EXAMPLES

1. Simple Plot

» > from pylab import *


» > from nwmpy import *
» > def f(t):
fl=(exp(- t)*sin(2*pi*t»
retu rn fl

» > tl=arange( O . O , 4 .0 , 0 .0 1 )
» > plot(tl, f(tl»
[<matplotlib.lines.Line2D object at Ox05C9D790>]
» > plot(tl , f(tl»
[<matplotlib.lines.Line2D object at Ox05D66E70>]
» > show()
3. Subplots 4. Different Plots

» > # subplots
» > from pylab import *
» > from numpy import *
» > def f(t) :
» > # d if fe ren t p lots
f1 = exp(- t)*sin(2*pi*t)
return f1 » > f r om pylab imp or t *
» > def f(t):
» > t1 = arange(O.O, 4.0, 0.01) fl=exp(- t)*sin(2*pi*t)
» > t2 = arange(O.O, 8.0, 0.01) return fl
» > subplot (211)
<matplotlib.axes.AxesSubplot object at Ox05BF8E10>
» > title('First Plot Exponential sinus') » > tl=arange(O . O, 4.0 , 0 . 05 )
<matplotlib.text�Text object at Ox05C10DFO> » > plot(tl, f(tl), 'bs', tl, 2*f(tl), 'g + ' )
» > xlabel('Fir st_Plot X label t') [ <matplotlib.lines.L ine2 D object at Ox0 5 B FE4FO>
<matplot1ib.text.Text object at Ox05C04490> » > show()
» > ylabel('First Plot Ylabel f (t) ')
<matplotlib.text.Text object at Ox05C10550>
» > plot(t1, f(t1))
[<matplotlib.lines.Line2D object at Ox05C1FBDO>]
» > subp1ot(212)
<matplotlib.axes.AxesSubplot object at Ox05D 1 ACFO>
» > title('Second Plot Exponential sinus')
<matplotlib.text.Text object at Ox05D28E30>
» > xlabel('Second_Plot Xlabel t ' )
<matplot1ib.text.Text object at Ox05D203DO>
» > ylabel('Second Plot Ylabel f (t) ')
<matplotlib.text.Text object at Ox05D28490> Fi g u re 1

» > plot(t2, f(t2))


[<matplotlib.lines.Line2D object at Ox05D8AF50>]
� 00 +
» > show()
2.0 r--�--�--�-�-----'

1.5
Figure 1 + +

� 0 C + 1.0

- +
- -
+.
0_5

First Plot Exponential Sinus

- ...-.+..
- -
0.0 - -

+- -
-
05
. .... +

+ +

- L�.':
o-: ----o:':
-; .5,---:++'-
:: 1--- :-'.0:--71.'::- 5----:
2"'::: .0,-------
-- 0 --:;-3'::- .5-----
2:':-; .5:---3"".:- 4.0-:"

First_Plot Xlabel t
x=2.87097 y=0.649685
Second Plot Exponential Sinus

OJ
.Q
'"
>= 0.2
'0
0:: 0.0
I
-g -0.2
e -0.4
ClJ 5. LinlIog Plots
'" -0.6
0=-----1-, :-----=-
2-, -3=---:-4 ----=- 6-----=
5 ----=- 7----:8
Second_Plot Xlabel t

» > # lin-log plot


» > from pyl ab import *
» > def f(t):
f1= exp(-t)*sin(2 * pi*t)
retu r n f1

» > t1= ar ange(0.1, 10.0, 0.01)


» > semilogx(t1,abs(f(t1)))
[ <matplotlib.lines . Line2D object at O x0 5 D2 6 5 10> ]
» > show()
4

riI\l F i g u re 1 7. Polar Plots

fDl' OO + » > #pol ar plot


» > from p ylab import *
» > theta =2*pi *a ran ge( O,lO,O . lO)
» > rho =O . 2 + cos(theta)
» > polar(theta, rho)
( <matplotlib.lines. Line 2 D object at O x0 5 C FC 9 7 0> ]
» > show ()

Fi g u re 1

-& 0 C +
90'

10'

6. Logllog Plots 180' 0'

» > #log-log-plots
» > from pylab import *
» > de f f(t):
f1=exp(-t)
return f1

» > t1=arange(0.1 , 10.0 , 0 . 01)


» > loglog(t1 , abs(f(t1 » )
270'
[ <matplotlib.lines.Line2D object at Ox05C4A510> ]
» > title('log-log p resentation')
<matplotlib.text.Text object at Ox05C42310>
» > xlabel('t')
<matplotlib.text.Text object at Ox05C36530>
» > ylabel('f ( t ) ') 8. Contour Plots
<matplotlib.text.Text object at Ox05C425 FO>
» > show()
» > * con tour plot
» > f rom pylab import *
» > x=arange(O, 6.28, 0 . 01)
» > y=arange(O, 3.14, 0 . 01)
Figure 1 » > X,Y=meshgrid(x,y)
» > Z= sin(X)*cos(Y+ pi/ 2)
� 0 C+ » > contour(X, Y, Z, linewi dths=2)
<matp lotlib . contour.QuadContourS et instance at Ox05C3CEB8>
log - l og p rese ntatio n
10° r= == ==========������� --
---- --�
-- » > show()

Figure 1

� OC+

3.0

2.5·

2.0

100 10' I.'

x=6.17053 y=0.119023
1.0

0.'

0.0
0

x=1.75712 y=1.95954
9. Contour Plots Fi g u re 1

� 0C +

» > *contour plot2


» > f rom pylab import *
1.0
» > x=arange(O, 6.28, 0.01)
» > y=arange(O, 3. 1 4, 0.01)
0.5
» > X, Y=meshgrid(x, y)
» > Z =sin(X)*cos(Y+pi/ 2)
0.0
» > contour(X, Y, X)
<matplotlib.contour.QuadContourset instance at O x0 5F2 F 9 B8>
» > show() -0.5

-1.0

x=4.95748 • y=5.3992 • z=·0.133042

.'.1 Figure 1
� 0 () +

3.0

2.5

11. Colormesh Levels


2.0

1.5

1.0

0.5
» > import matplotlib.pyplot as pIt
» > from matplotlib.colors import BoundaryNorm
0.0 ;'__-L:-_.L.---::-_L-_7-__--';__--'-�-...L.--;
,-J
0 » > from matplotlib.ticker import MaxNLocator
» > import numpy as np
-
» > dx, dy = 0.02, 0.02
» > y, x = np.mgrid [ slice(1, 5 + dy, dy) ,
slice(1, 3 + dx, dx) )
» > z = np.sin(x) ** 10 + np.cos(10 + y * x) * np.cos(x)
» > z = z [:-1, : -1)
» > levels = MaxNLocator(nbins=15).tick- values(z.min(), z.max())
» > cmap = plt.get cmap('p iYG')
» > norm = Boundary Norm(l evels, ncolors=cmap.N, clip=T rue)
» > pIt.subplot(2, 1, 1)
<matplotlib.axes.AxesSubplot object at Ox05E099FO>
10. 3D Plot » > im = plt.pcolormesh(x, y, z, cmap=cmap, norm=norm)
» > plt.colorbar()
<matplotlib.colorbar.Colorbar instance at Ox0609C990>
» > plt.axis( [x.min() , x.max() , y.min() , y.max() ))
[1.0, 3.0, 1.0, 5.0)
» > plt.title('pcolormesh with levels')
<matplotlib.text.Text object at Ox05FSF150>
* 3 D plot
import numpy as np » > pIt.subplot(2, 1, 2)
from matplotlib import em <matplotlib.axes.AxesSubplot object at Ox060A2C30>
from mpl toolkits .mplot3d import Axes3D » > plt.contourf(x [ : -1, : -1) + dx/ 2.,
p
from mat lotlib import pyplot as pIt
y [ : -1, : -1) + dy/ 2., z, levels=levels,
fig=plt.figure()
ax=fig.gca(projection='3d')
cmap=cmap)
X=np.arange(-5, 5, 0.25) <matplotlib.contour.QuadContourSet instance at Ox060AF9EO>
Y=np.arange(-5, 5, 0.25) » > plt.colorbar()
X, Y = np.meshgrid(X, Y)
<matpl otlib.colorbar.Colorbar instance at Ox06234AAS>
R = np. sqrt(X**2 + Y**2)
Z = np.sin { R)
» > plt.title('contourf with levels')
surf = ax.plot surface(X, Y, Z, rstride=l , cstride=l , cmap=cm.coolwarm) <matplotlib.text.Text object at Ox060D64BO>
-
plt.show() » > plt.show()
6

1.2 V. CONCLUSION
0.9 The effect of the globalization and improvements on using
0.6 technology are issuing various areas of research and studies.
0.3 As technology improves the developers also getting more ex­
0.0 perienced. The development of latest progranuning languages
-0.3 are being implemented. Current programming languages and
-0.6 softwares are able to solve a lot of experiments on numerical
-0.9 computations. One of this programming language is Python
which having matplotlib module and offering types of advan­
1.2 tages on numerical computational researches and applications.
0.9 By using recent implementation of pythons matplotlib some
0.6 numerical examples are experimented. As the module im­
0.3 proves it would be possible to apply various types of numerical
0.0 calculations.
-0.3

-0.6 REFERENCES
-0.9
[I] James Stewort,Calculus. California 1991,ISBN 0-534-13212-x
[2] S. Bruce P. Conrad, Differential Equations with Boundary Value Prob­
lems. Pearson Education,Prentice Hall,2003,IBSN 0-13-093419-4
[3] S. Lipschutz,Linear Algebra Schaum's Solved Problems Series. McGraw
Hill 1989
[4] Sullivan Sullivan, College Algebra. Pearson,New Jersey,2006
[5] Niyazi ARI, Python [or Engineers. Lecture Notes University of Tech-
12. 3D Polygon
nology,Zurich,Switzerland,2006
[6] http://en. wikipedia.org/wiki/Python_%28programmin�language%29
[7] http;llphillipmfeldman.orgiPythoniAdvantages_oCPython_Over_Matlab.html
» > import mpl_tool kits.mplot3d as m3d
[8] http://en.wikipedia.org/wiki/Matplotlib
» > import matplotlib.colors as m col [9] http;llmatplotlib.orgi
» > import pylab as pypl [l0] http;llmatplotlib.orgll.3.lIuserslintro.html
» > import scipy as pysp [11] http://metarabbit. wordpress.com/20 13/10/18/why-python-is-better-than­
» > ax = m3d. Axes3D(pypl. figure(» matlab-for-scientific-softwarel
[12] http://jakevdp.github.iolblogl2013/03/23/matplotlib-and-the-future-of­
» > fo r i in range ( 7 ) :
visualization-in-pythonl
vtx = pysp.rand(3,3)
[13] http;llnbviewer.ipython.org/github/jrjohanssoniscientific-python­
tri = m3d.art3d. Poly3D Collection( [ vtx ] ) lectureslblob/masterlLecture-4-Matplotlib.ipynb
tri.set_color(mcol.r gb2hex(pysp . rand(3») [14] http://stackoverflow.com
tri.set_edgecolor( ' k ' )
ax.add_collection3d(tri)

» > pypl.show()

Fi g u re 1

-fiil' 00 +

10
.

08
.

0.6

0.4

0.2

0.0

1.0
0.8

0.4
0.2
0.8
1.0 00
x=1.00935 , y=0.00522854 , z=0.264117

You might also like