Numpy and Matplotlib: Purushothaman.V.N March 10, 2011
Numpy and Matplotlib: Purushothaman.V.N March 10, 2011
Introduction
Concept of high level language A high level programming language is a set of well dened notations which is capable of expressing algorithms. The notations selected must be suitable for the problems to be solved. In general a high level language should have the following features. Concept of high level language 1. Ability to represent dierent data types like characters, integers and real numbers. In addition to this it should also support a collection of similar objects like character strings, arrays etc. 2. Arithmetic and Logical operators that acts on the supported data types.
3. Control ow structures for decision making, branching, looping etc. 4. A set of syntax rules that precisely specify the combination of words and symbols permissible in the language. 5. A set of semantic rules that assigns a single, precise and unambiguous meaning to each syntactically correct statement. Compilers A compiler is a computer program that translates source code into object code. It takes as input the specication for an executable program and produces as output the specication for another, equivalent executable program. Interpreters An interpreter translates some form of source code into a target representation that it can immediately execute and evaluate. The structure of the interpreter is similar to that of a compiler, but the amount of time it takes to produce the executable representation will vary with the amount of optimization. comparison :compiler vs Interpreter 1 compiler Spends a lot of time analyzing and processing the program The resulting executable is some form of machinespecic binary code The computer hardware interprets (executes) the resulting code Program execution is fast interpreter Relatively little time is spent analyzing and processing the program The resulting code is some sort of intermediate code The resulting code is interpreted by another program Program execution is relatively slow
Advantages of Python in comparison with other Languages Python is a simple, high level language with a clean syntax. It oers strong support for integration with other languages and tools. It has extensive standard libraries, and can be learned in a few days. Python programmers report substantial productivity gains. They feel the language encourages the development of higher quality, more maintainable code Dierent methods of using python: Interactive mode Python can be used in the interactive mode (shell mode) as a programmable calculator capable of even plotting graphs. If you issue the command python, without any argument, from the command prompt, the Python interpreter will start and display a >>> prompt where Python commands and statements can be typed. This method is useful only for viewing the results of single Python statements. >>> a=10 >>> b=5 >>>a*b 50 >>> a+b 15 Dierent methods of using python: File mode For large programs, the le-mode or edit mode is preferred. In this mode, source code is entered in a text editor or a front-end for python like IDLE. The le is then saved with a name having extension .py. To run the program it is then called as python lename.py Example. First.py a=10 b=5 print a*b print a+b
Save it as rst.py in a suitable directory and run the le as python rst.py at the command prompt or using front end. The output screen will show 50 15
Inputs A program is a set of statements used to produce an output from the input data. Numbers, real and complex, are read from terminal using the function input(Prompt) . Strings are read using the function raw input(prompt). For example >>> b=input(Give a number: ) Give a number: 10 >>>> b 10 >>> a=raw_input(Give a text: ) Give a text: hopeless >>> a hopeless Outputs The output of a program can be a number, text or graphics. For text and numbers print statement is employed. For graphic output functions like show(),saveg() etc are dened in relevant modules. >>> x=5 >>> print x 5 >>> y=[2,5,7,9] >>> print y [2, 5, 7, 9] >>> z=beamer >>> print z beamer >>> print x,y,z 5 [2, 5, 7, 9] beamer
Variables and data types A computer program to solve a problem is designed using variables belonging to the supported data types. Python supports numeric data types like integers, oating point numbers and complex numbers. To handle character strings, it uses the String data type. Python also supports other compound data types like lists, tuples, dictionaries. In the previous slide, x is numeric, y is a list and z is a string. Operators Operators are functionality that do something and can be represented by symbols such as + or by special keywords. Operators require some data to operate on and such data are called operands. In x = 2 + 3,2 and 3 are the operands and = and + are operators.. The other operators are or,and,not(Boolean OR,AND,NOT) in(Membership), not in(Non-membership), <, <=, >, >=, !=, == (Comparisons) |,^,&(Bitwise OR, XOR,AND), <<, >>(Bitwise Shifting left and right) +,-,* (Add, Subtract, Multiply) /,%,**(divide, reminder, Exponentiation) +x (Positive), -x(Negative), ~(Bitwise NOT), x[index](Subscription) Strings String is a collection of same kind of elements (characters). It is a compound, or collection, data type. The individual elements of a String can be accessed by indexing. >>> >>> h >>> o >>> >>> d s = hello world s[0] s[7] s[5] s[-1] # will print the last character
Strings can be added and multiplied. >>> p,q,r=Eating ,troubles, meeting >>> p+q+r Eating troubles meeting >>> 2*p+q Eating Eating troubles Mutable and Immutable Types There is one major dierence between String and List types. List is mutable but String is not. We can change the value of an element in a list, add new elements to it and remove any existing element. This is not possible with String type. Lists List is much more exible than String. The individual elements can be of any type, even another list. Lists are dened by enclosing the elements inside a pair of square brackets and separated by commas. >>> l=[2.3,A,3,khan] >>> type(l) <type list> >>> 2*l [2.29, A, 3, khan, 2.29, A,3, khan] >>> l[3]=28 >>> l [2.299, A, 3, 28] Tuples Tuples are data structures that are very similar to lists, but they cannot be modied (immutable). They can only be created. Tuples have important roles as keys for dictionaries. A tuple is a sequence that is enclosed by parentheses ( ). The following line of code creates a three-element tuple >>> x = (a, b, c) Interconversion between lists and tuples is possible using list() and tuple() functions.
>>> list((1, 2, 3, 4)) [1,2, 3, 4] >>> tuple([1, 2, 3, 4]) (1,2, 3, 4) Dictionaries Dictionaries are associative arrays. It is a group of {key : value} pairs. The elements in a dictionary are indexed by keys. Keys in a dictionary are required to be unique. Keys can be almost any Python type, but are usually numbers or strings. Values, on the other hand, can be any arbitrary Python object. Dictionaries are enclosed by curly braces - { } and values can be assigned and accessed using square braces []. They are dierent from sequence type containers like lists and tuples in the method of storing data. There is no concept of order among elements. They are unordered. Example for a dictionary is given below. >>> dct={} #Creates an empty dictionary >>> dct[host]=Earth #host is the key and earth is the value. >>> dct {host: Earth} >>> dct[port]=80 >>> dct {host: Earth, port: 80} >>> dct.keys() [host, port] >>> dct.values() [Earth, 80] >>> print dct[host] Conditional Execution The most fundamental aspect of a progamming language is the ability to control the sequence of operations. One of this control is the ability to select one action from a set of specied alternatives. The other one is the facility to repeat a series of actions any number of times or till some condition becomes false. To execute some section of the code only if certain conditions are true python uses if, elif, elif,...,else construct. >>> x = input(Enter a number ) 10 7
>>> if x>10: print x>10 # Note the Colon and indentation. elif x<10: print x<10 else: print x=10 x=10 Iteration and looping when a condition remains true, if a set of statements are to be repeated, the while and for constructs are employed. The general syntax of a while loop may be given as follows. while condition: set of statements to be repeated for elements in list or tuple : set of statements to be repeated >> x=10 >>> while x>0: print x, x=x-1 10 9 8 7 6 5 4 3 2 1 >>> for i in range(10,0,-1): print i, 10 9 8 7 6 5 4 3 2 1 Functions and Modules A function is a block of code that performs a specic task. Using a function in a program is called calling the function. In python a function is dened using the keyword def >>> def large(x,y,z): if y>x: x,y=y,x if z>x: z,x=x,z return(x) >>> large(3,4,2) 4
A collection of functions is a module. eg. math, os,random, pylab, numpy etc File input and Output Files are used to store data and program for later use. This program creates a new le named t.txt (any existing le with the same name will be deleted) and writes a String to it. The le is closed and then reopened for reading data. >>> f=open(t.txt,w) >>> f.write(breaking into the file) >>> f.close() >>> f=open(t.txt,r) >>> f.read() breaking into the file Pickling Strings can easily be written to and read from a le. Numbers take more eort, since the read() method only returns Strings, which will have to be converted into a number explicitly. However, it is very complicated when trying to save and restore data types like lists, dictionaries etc. Rather than constantly writing and debugging code to save complicated data types, Python provides a standard module called pickle. pickle.dump(a,f ) will save a to le f. a=pickle.load(f) retrieves data from le f. Pickling- Examples >>>import pickle >>>a=10.1 >>>b=sh >>>c=[5,3,2] >>>f = open("state", w) >>>pickle.dump(a, f) pickle.dump(b, f) pickle.dump(c, f) file.close() >>>file = open("state", r) Reading and writing files a = pickle.load(file) 9
b = pickle.load(file) c = pickle.load(file) file.close() Any data that was previously in the variables a, b, or c is restored to them by pickle.load.
NumPy
Introduction NumPys main class is the homogeneous multidimensional array called ndarray. This is a table of elements (usually numbers), all of the same data type. Each element is indexed by a tuple of positive integers. Examples of multidimensional array objects include vectors, matrices, spreadsheets etc. The term multidimensional refers to arrays having several dimensions or axes. The number of axes is often called rank ( not a tensor rank). For example, the coordinates of a point in 3-D space (x, y, z) is an array of rank 1. This also gives the position vector of that point. The array 1 0 0 (it ([1., 0., 0.], [0., 1., 2.]) is one of rank 2. It is equivalent to 0 1 2 is 2-dimensional). The rst dimension (rows) has a length of 2, the second dimension(column) has a length of 3. Array creation There are many ways to create arrays. For example, you can create an array from a regular Python list or tuple using the array function. >>> a = array( [2,3,4] ) >>> a array([2, 3, 4]) >>> type(a) # a is an object of the ndarray class <type numpy.ndarray> Array transforms sequences of sequences into two dimensional arrays, and it transforms sequences of sequences of sequences into three dimensional arrays, and so on. The type of the resulting array is deduced from the type of the elements in the sequences. >>> b = array( [ (1.5,2,3), (4,5,6) ] ) >>> b 10
array([[ 1.5, [ 4. ,
2. , 5. ,
3. ], 6. ]])
The important attributes of any ndarray object b are: 1. b.ndim :It gives the rank of the array. 2. b.shape:It returns a tuple of integers indicating the size of the array in each dimension. For a matrix with m rows and n columns, shape returns (m, n). 3. b.size. Returns the total number of elements in all dimensions of the array. This is equal to the product of the elements of shape.
4. b.dtype Returns the data type of the elements in the array. NumPy provides the following datatypes: bool, character, int, int8, int16, int32, int64, f loat, f loat8, f loat 5. b.itemsize: Returns the size in bytes of each element of the array.For example, an array of elements of type oat64 has itemsize 8 (=64/8), while one of type complex32 has itemsize 4 (=32/8). 6. b.data: Returns the buer containing the actual elements of the array. Example for these methods : We dene the following array: >>> from numpy import * >>> a = array([(0, 1, 2),(3, 2, 1)],) >>>a.shape, a.ndim, a.size, a.itemsize, a.dtype ( (2, 3), 2, 6, 4, dtype(int32) ) The type of the array can also be explicitly specied at creation time: >>> c = array( [ [1,2], [3,4] ], dtype=complex ) >>> c array([[ 1.+0.j, 2.+0.j], [ 3.+0.j, 4.+0.j]]) >>> c.dtype dtype(complex128) A frequent error consists in calling array with a multiple numeric arguments, rather than providing a single list of numbers as an argument.
11
>>> a = array(1,2,3,4) # WRONG because numbers within () are taken as arguement >>> a = array([1,2,3,4]) \# RIGHT because [1,2,3,4] is a single list. The function array is not the only one that creates arrays. Usually the elements of the array are not known from the beginning, and a placeholder array(empty array) is needed. There are some functions to create arrays with some initial content. By default, the type of the created array is oat64. The function zeros(m,n) creates an array full of zeros, the function ones(m,n) creates an array full of ones, the function empty(m,n) creates an array without lling it in and the function random(m,n) creates an array lling it with random numbers between 0 and 1. Then the initial content is random and it depends on the state of the memory. In these functions the arguments m, n species the shape of the array. To create an array whose elements are sequences of numbers, NumPy provides a function arange(x1 , x2 , dx) and returns x1 , x1 + dx, ...., x2 dx. It is analogous to range but accepts oating point numbers also. >>> arange( 10, 30, 5 ) array([10, 15, 20, 25]) >>> arange( 0, 2, 0.3 ) array([ 0. , 0.3, 0.6,
0.9,
1.2,
1.5,
1.8])
Using arange with oating point arguments, it is generally not possible to predict the number of elements obtained because of the oating point precision. Hence it is better to use the function linspace(x1 , x2 , nx) and returns equispaced nx numbers from x1 to x2 . An empty array can be created with a specied shape using empty() function. empty (shape=, dtype=int) Return an uninitialized array of data type, dtype, and given shape. An array of zeros can be created with a specied shape using zeros() function. zeros(shape=, dtype=):Return an array of data type dtype and given shape lled with zeros. An array of ones can be created with a specied shape using ones() function. zeros(shape=, dtype=): Return an array of data type dtype and given shape lled with zeros. an identity matrix can be created using identity() function identity (n, dtype=intp): Return a 2-d square array of shape (n,n) and data type, dtype with ones along the main diagonal. >>> empty( (2,3) ) array([[ 3.73603959e-262, 6.02658058e-154, 12 6.55490914e-260],
5.30498948e-313,
3.14673309e-307,
1.00000000e+000]])
>>> empty( (2,3) ) # the content may change in different invocations array([[ 3.14678735e-307, 6.02658058e-154, 6.55490914e-260], [ 5.30498948e-313, 3.73603967e-262, 8.70018275e-313]]) >>> zeros( (3,4) ) array([[0., 0., 0., [0., 0., 0., [0., 0., 0., >>> ones( array([[[ [ [ [[ [ [ (2,3,4), 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
>>> a=identity(4,dtype=float) >>> a array([[ 1., 0., 0., 0.], [ 0., 1., 0., 0.], [ 0., 0., 1., 0.], [ 0., 0., 0., 1.]]) >>> linspace( 0, 2, 9 ) array([ 0. , 0.25, 0.5 , 0.75, 1. , 1.25, 1.5 , 1.75, 2. ]) >>> x = linspace( 0, 2*pi, 10 ) >>> x array([ 0. , 0.6981317 , 1.3962634 , 2.0943951 , 2.7925268 , 3.4906585 , 4.1887902 , 4.88692191, 5.58505361, 6.28318531]) >>> f = sin(x) array([ 0.00000000e+00, 6.42787610e-01, 9.84807753e-01, 8.66025404e-01, 3.42020143e-01, -3.42020143e-01, -8.66025404e-01, -9.84807753e-01, -6.42787610e-01, -2.44921271e-16])
13
14
The reshape function returns its argument with a modied shape, whereas the resize method modies the array itself: Printing arrays When you print an array, NumPy displays it in a similar way to nested lists, but with the following layout: 1. the last dimension is printed from left to right, 2. the last but one, from top to bottom, 3. and the rest, also from top to bottom, separating each slice by an empty line. One dimensional arrays are then printed as rows, two dimensional as matrices and three dimensionals as lists of matrices. >>> a = arange(6) >>> print a [0 1 2 3 4 5] >>> >>> b = arange(12).reshape(4,3) >>> print b [[ 0 1 2] [ 3 4 5] [ 6 7 8] [ 9 10 11]] >>> >>> c = arange(24).reshape(2,3,4) >>> print c [[[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11]] [[12 13 14 15] [16 17 18 19] [20 21 22 23]]] If an array is too large to be printed, NumPy automatically skips the central part of the array and only prints the corners: >>> print arange(10000) 15
[ 0 1 2 ..., 9997 9998 9999] >>> >>> print arange(10000).reshape(100,100) [[ 0 1 2 ..., 97 98 99] [ 100 101 102 ..., 197 198 199] [ 200 201 202 ..., 297 298 299] ..., [9700 9701 9702 ..., 9797 9798 9799] [9800 9801 9802 ..., 9897 9898 9899] [9900 9901 9902 ..., 9997 9998 9999]] Saving and restoring arrays The simplest way to store arrays is to write it to a text le as text using the numpy function savetxt(). The array can be retrieved using the function genfromtxt(). The syntax of these functions are savetxt(fname,array,fmt= ,delimiter=) Here fname is the name of the le to be created and opened for writing, array is the name of the array, fmt is the format specication of the data to be stored, delimiter is the character used to distinguish elements of the array. genfromtxt(fname,dtype=,comments=# ,delimiter= ,skiprows= ). Here dtype is the datatype of array elements and skiprows accepts a number which refers to the number of rows to skip from 0th row. >>> b array([[ 0., 1., 2., 3.], [ 4., 5., 6., 7.], [ 8., 9., 10., 11.], [ 12., 13., 14., 15.]]) >>> savetxt(f1.txt,b,fmt=%8.6f,delimiter=&) >>> savetxt(f2.txt,b,fmt=%8.4f,delimiter= )
When f1.txt and f2.txt are opened in a text editor, the contents of the file will f1.txt 0.000000 &1.000000 &2.000000 &3.000000 4.000000 &5.000000 &6.000000 &7.000000 8.000000 &9.000000 &10.000000&11.000000 12.000000&13.000000&14.000000&15.000000 f2.txt 0.0000
1.0000
2.0000
3.0000 16
>>> genfromtxt(f1.txt,dtype=float) array([[ 0., 1., 2., 3.], [ 4., 5., 6., 7.], [ 8., 9., 10., 11.], [ 12., 13., 14., 15.]]) >>> genfromtxt(f1.txt,skiprows=2) array([[ 8., 9., 10., 11.], [ 12., 13., 14., 15.]])
If the arrays are too large, saving them in text format consumes large volume of memory. In that case they can be saved in binary format.
>>> from numpy import * >>> a=genfromtxt(f1.txt) >>> save(f3.npy,a) When the file f3.npy is opened in a word processor, the following output is obtai 1 2 NUMPY##F#{descr: <f8, fortran_order: False, shape: (4, 4), } ############## 2 ?#######@#######@#######@#######@#######@#######@###### @###### 1 >>> b=load(f3.npy) >>> b array([[ 0., 1., 2., [ 4., 5., 6., [ 8., 9., 10., [ 12., 13., 14.,
Basic Operations Arithmetic operators apply elementwise on arrays. A new array is created and lled with the result. >>> a = array( [20,30,40,50] ) >>> b = arange( 4 ) >>>b array([0,1,2,3]) 17
>>> c = a-b >>> c array([20, 29, 38, 47]) >>> b**2 array([0, 1, 4, 9]) >>> 10*sin(a) array([ 9.12945251, -9.88031624, 7.4511316 , -2.62374854]) >>> a<35 array([True, True, False, False], dtype=bool) Unlike in many matrix languages, the product operator * operates elementwise (product of corresponding elements) in NumPy arrays. The matrix product can be performed using the dot function. It also gives the dot product of two vectors. Similarly a cross function is dened which returns the cross product of two vectors. outer (x, y) computes an outerproduct of two vectors (zij = xi .yj ). The function inner (x,y) computes the inner product between two arrays. r[I, J] = a[I, k]b[J, k]. >>> from numpy import* >>> A = array( [[1,1],[0,1]] ) >>> B = array( [[2,0],[3,4]] ) >>> A*B array([[2, 0], [0, 4]]) >>> dot(A,B) array([[5, 4], [3, 4]]) >>> mat(A)*mat(B) matrix([[5, 4], [3, 4]]) >>> x=([1,2,3]) >>> y=([3,2,1]) >>> dot(x,y) 10 >>> cross(x,y) array([-4, 8, -4]) >>> inner([1,2,3],[10,100,1000]) 3210 # 1.10+2.100+3.1000 >>> a=arange(9).reshape(3,3) >>> b=a.T 18
>>> a array([[0, 1, 2], [3, 4, 5], [6, 7, 8]]) >>> b array([[0, 3, 6], [1, 4, 7], [2, 5, 8]]) >>> inner(a,b) array([[ 15, 18, 21], [ 42, 54, 66], [ 69, 90, 111]])
It is possible to perform increment and decrement operations without creating new arrays. >>> a = ones((2,3), dtype=int) #integer array >>> b = random.random((2,3)) #float array >>> a *= 3 >>> a array([[3, 3, 3], [3, 3, 3]]) >>> b += a >>> b array([[ 3.69092703, 3.8324276 , 3.0114541 ], [ 3.18679111, 3.3039349 , 3.37600289]]) >>> a += b \# b is converted to integer type >>> a array([[6, 6, 6], [6, 6, 6]]) When operating with arrays of dierent numeric data types, the type of the resulting array corresponds to the more general or precise one. >>> a = ones(3, dtype=int32) >>> b = linspace(0,pi,3) >>> b.dtype.name float64 >>> c = a+b >>> c array([ 1. , 2.57079633, 19
4.14159265])
>>> c.dtype.name float64 >>> d = exp(c*1j) >>> d array([ 0.54030231+0.84147098j, -0.84147098+0.54030231j, -0.54030231-0.84147098j]) >>> d.dtype.name complex128 Many unary operations, like computing the sum of all the elements in the array, are implemented as methods of the ndarray class. >>> a = random.random((2,3)) >>> a array([[ 0.6903007 , 0.39168346, [ 0.48819875, 0.77188505, >>> a.sum() 3.4552372100521485 >>> a.min() 0.16524768654743593 >>> a.max() 0.9479215542670073
0.16524769], 0.94792155]])
By default, these operations apply to the array as if it were a list of numbers, regardless of its shape. However, by specifying the axis parameter you can apply an operation along the specied axis(dimension) of an array: >>> b = arange(12).reshape(3,4) >>> b array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]) >>> >>> b.sum(axis=0) array([12, 15, 18, 21]) >>> >>> b.min(axis=1) array([0, 4, 8]) >>> >>> b.cumsum(axis=1) array([[ 0, 1, 3, 6], [ 4, 9, 15, 22], [ 8, 17, 27, 38]]) 20
Linear Algebra
The linear algebra module is a subclass of numpy. It is called linalg. A few functions are dened in the numpy.linalg sub-package. The important functions are 1. norm(x): Returns norm of a vector x, norm = 2. det(a): Returns determinant of a square matrix 3. inv(a): Returns inverse of a non-singular square matrix 4. pinv(a): Returns pseudo inverse of a singular square matrix. For invertible matrices, this is the same as the inverse. 5. solve(a,y): Returns the solution vector x to the linear equation ax = y 6. eig(a):Return all solutions (, x) to the equation ax = x. The rst element of the return tuple contains all the eigenvalues. The second element of the return tuple contains the eigenvectors (ith eigenvector as ith column). 7. eigvals(a): Returns all eigenvalues of square matrix a as an array 8. eigh(h): Return all solutions (, x) to the equation hx = x where h is a hermitian matrix. 21 x2 i
9. eigvalsh(h):Returns all eigenvalues of hermitian matrix h as an array 10. trace(a): Returns trace of a square matrix. These are also included in the sub-package numpy.dual. 1 1 2 Let a be a square matrix 1 0 1. It is created as 2 3 0 >>> from numpy import* >>> from numpy.linalg import* >>> a=array([[1,0,1], [2,1,0], [0,2,4]]) >>> det(a) 8.0 >>> inv(a) array([[ 0.5 , 0.25 , -0.125], [-1. , 0.5 , 0.25 ], [ 0.5 , -0.25 , 0.125]]) >>> y=([2,3,1]) >>> solve(a,y) array([ 1.625, -0.25 , 0.375]) >>> eigvals(a) array([ 0.8223493+1.07730381j, 0.8223493-1.07730381j, 4.3553014+0.j]) >>> eig(a) (array([ 0.8223493+1.07730381j, 0.8223493-1.07730381j, 4.3553014+0.j #eigenvalues array([[-0.06908062+0.41891651j, -0.06908062-0.41891651j, [ 0.77771286+0.j , 0.77771286+0.j , [-0.43902814-0.14884162j, -0.43902814+0.14884162j, # Three eigenvectors
]),
Matplotlib
Data visualization Graphs, charts, surface plots etc are visual presentations of numerical data. It is useful to compare, contrast, detect trends, predict and understand huge amounts of data. Dierent Python modules are used for generating two and three dimensional graphs. 22
The Matplotlib Module The python package Matplotlib produces graphs and gures dierent hardcopy formats like jpeg, bmp, eps, ps etc. It also provides many functions for matrix manipulation. The data points to the plotting functions are supplied as Python lists or Numpy arrays. from matplotlib.pyplot import* from numpy import* x=range(10) y=[a*a-a for a in x] plot(x,y) show()
80 70 60 50 40 30 20 10 0 0 1 2 3 4 5 6 7 8 9
By default, the color is blue and the line style is continuous. This can be changed by an optional argument after the coordinate data, which is the format string that indicates the color and line type of the plot. The default format string is b- (blue, continuous line). Let us rewrite the above example to plot using red circles. We will also set the ranges for x and y axes and label them. Multiple plots: Matplotlib allows you to have multiple plots in the same window, using the subplot(nr,nc,nf ) command. The arguments nr is the number of rows and nc is the number of columns in a single window. nf is the gure number, that ranges from 1 to nr nc. Example from matplotlib.pyplot import* from numpy import* subplot(2,2,1) plot([1,2,3,4],*-) subplot(2,2,2) plot([4,2,3,1],^-) subplot(2,2,3) plot([4,3,2,1],^-) subplot(2,2,4) 23
plot([2,4,3,1],^-) show()
4.0 3.5 3.0 2.5 2.0 1.5 1.0 0.0 4.0 3.5 3.0 2.5 2.0 1.5 1.0 0.0 4.0 3.5 3.0 2.5 2.0 1.5 1.0 0.0 4.0 3.5 3.0 2.5 2.0 1.5 1.0 0.0
0.5
1.0
1.5
2.0
2.5
3.0
0.5
1.0
1.5
2.0
2.5
3.0
0.5
1.0
1.5
2.0
2.5
3.0
0.5
1.0
1.5
2.0
2.5
3.0
Polar plots: Polar coordinates locate a point on a plane with one distance and one angle. The distance r is measured from the origin. The angle is measured from positive direction of x-axis in the anti-clockwise sense. Plotting is done using polar(theta, radius, f ormat string) function. from matplotlib.pyplot import* from numpy import* th = linspace(0,2*pi,100) r = 4 * ones(100) # radius = 5 polar(th,r,r*) show()
135
270
225
315
180
0.5
1.0
2.0 1.5
2.5
3.0
3.5
45 4.0 0
90
24
Polar rhodonea A rhodonea or rose curve is a sinusoid r = sin (n) where n is a constant. If n is an integer the curve will have 2n petals and n petals if n is odd. If n is a rational number(=p/q, p,q integers), then the curve is closed and has nite length. If n is an irrational number, then it is closed and has innite length. from matplotlib.pyplot import* from numpy import* n=2 th = linspace(0, 10*pi,1000) r = sin(n*th) polar(th,r) show()
135
Pie Charts: A pie chart is a circular chart in which a circle is divided into sectors. Each sector visually represents an item in a data set to match the percentage or fraction of the item in the total data set. Pie charts are useful to compare dierent parts of a whole amount. They are often used to present nancial information. The function pie(list of percentages or fractions , labels=list of labels) produces a pie chart. Both the lists must have the same length. from matplotlib.pyplot import* from numpy import* labels = [A+, A, B+, B, C+, C,D] fracs = [5,8,18, 19, 20,17,14] pie(fracs, labels=labels) show()
270
225
315
180
45 1.0 0
90
25
B+ B
A A+
C+
Parametric plots: A parametric plot is a visual description of a set of parametric equations. If x and y are both functions of a variable t, then they create a set of parametric equations. For example, the two equations y = t sin t2 and x = t cos t2 form a set of parametric equations in which y and x are functions of t, the graph of which will be in this form. from matplotlib.pyplot import* from numpy import* t=arange(0,6.3,0.001) x=t*cos(t*t) y=t*sin(t*t) plot(x,y) show()
8 6 4 2 0 2 4 6 8 6 4 2 0 2 4 6 8
2-D plots in colours: Two dimensional matrix can be represented graphically by assigning a color to each point proportional to the value of that element. The function imshow(matrix) is employed to create such plots. from matplotlib.pyplot import* from numpy import* m=linspace(0,1,900).reshape(30,30) 26
imshow(m) show()
0
10
15
20
25
10
15
20
25
27