{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

lec6_Pylab_review

# lec6_Pylab_review -   Interactive plots   Plotting data...

This preview shows page 1. Sign up to view the full content.

This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview:   Interactive plots   Plotting data from a file   Practice Exercises   Review arrays and loops Class Notes   Be working on HW#2 – don’t wait until the night before!   You should be reading Chap. 4 through the week.   Make sure to come see me or gather with your classmates for help when you need it. If this is not coming naturally to you, you are not alone!   Vectors have both magnitude and direction.  On an x,y grid, the field will have both and x and y component. Use ‘meshgrid’ to create the 2D x,y grid.   quiver plot will plot the direction and magnitude of the field at each point. #create grid of points in x,y x,y=meshgrid(linspace (0,2*np.pi,30),linspace (0,2*np.pi,30)) U=sin(x) #x component V=cos(y) #y component quiver(x,y,U,V, sqrt(U**2+V**2)) title('Vector (quiver) plot of V_x=sin(x), V_y=cos(y)', fontsize=20) xlabel('x',fontsize=20) ylabel('y',fontsize=20)   For interacting, we need to look for ‘events’ like clicking or pressing a key and do something in response.  This is called binding events to a function and is done with the ‘connect’ function.   Types of events can be:  ’key_press_event’: returns what ever key pressed   ‘button_press_event’: returns the x and y coordinates of the location clicked and which button.   Several other types of events: see ‘help connect’   Here’s an example: plot a gaussian peaked where the user clicks. Make each new curve a random color and let user clear the curves with a ‘c’ press and quit with a ‘q’ press. def click(event): col=(rand(),rand(),rand()) xClick,yClick= event.xdata, event.ydata plot(x,gauss(x,A=yClick,x0=xClick),color=col) draw() def done(event1): if event1.key == 'q': close('all') if event1.key == 'c': clf() plot([0],[0] axis([0, 10, 0, 1]) draw() #now register the event to the above function cid = connect('button_press_event',click) cid1= connect('key_press_event',done) title("Click anywhere in the graph to draw a new Gaussian.\ \n Type 'q' to quit or 'c' to clear graph") xlabel("X") ylabel("Y") plot([0],[0]) #clears existing graphs axis([min(x), max(x), 0, 1]) show()   Often experimentalists will produce data which is stored in a plain text file.   Pylab (numpy actually) has convenient functions for reading from text files: loadtxt(‘myfile.txt’)   Returns a multidimensional array with columns of data. from pylab import * data = np.loadtxt( data.txt ) x=data[:,0] y=data[:,1] plot(x,y, go , label= My data ) legend(loc=(1.5,10.5)) xlabel( Time (years) ) ylabel( Population ) show()   Optional arguments: comment=‘#’, unpack=True, delimiters=‘,’, skiprows=2, … (see ‘help loadtxt’ for more)   Can download remote data files using urllib library: urllib.urlretreive(‘http://www.host.edu/datafile.dat’, filename=‘localcopy.dat’) #unpack all columns and assign to #variable right away T,E,G=np.loadtxt('YMS_moduli.dat', unpack=True) subplot(211) plot(T,E,'g-^',ms=7) ylabel('Young\'s Modulus (GPa)') subplot(212) plot(T,G,'b-^',ms=7) ylabel('Shear Modulus (GPa)') xlabel('Temperature (C)')   Saving array data generated in the program is just as easy using savetxt() function.   Can specify number format with standard printf strings and delimiter (‘\t’, ‘,’……) from pylab import * x=linspace(0,10,100) y=3.0*x**2-10.0*x+3.0 #x and y are ROW arrays XY=np.array([x,y]) #convert XY to COLUMN arrays for output in columns XYt=XY.transpose() np.savetxt('mydata.txt', XYt, fmt='%2.3e',delimiter = '\t')   Generate x and y arrays of length 50 where y= (x-2)**2*sin(x) from x=[0,10]   Write data to a file (‘mydata.txt’) in columns   Read data back in and plot with line joined green squares. Follow up  Find the minimum in the y data and print the (x,y) values where the minimum occurs on the plot.   Helpful array methods: y.argmin() produces the index where the minimum value in y occurs. Similar for y.argmax().   for loops   A ‘looping’ variable is created and referenced in the for loop. Does not exist anywhere else.   looping variable changes with each iteration of the loop   Nested loops: for loop inside another for loop for iterating 2 collections of data. for num1 in [1,2,3]: for num2 in [4,5,6,7]: print %g times %g = %g % (num1, num2,num1*num2)   Variables created inside functions are LOCAL in scope. Meaning they are only known inside the function.  Variables created outside functions (in the main part of the program ARE known within functions. They are GLOBAL in scope.  Can force a local variable to be globally known using: ‘global var_name’ inside function, but it is not good practice. def funct(): a=2 print Inside function: a= , a return a=1 print Outside function: a= , a funct() print Outside function: a= , a   However, changes made to lists, dictionaries, etc. inside the function ARE reflected outside the function.   Careful with arrays – changes in specific elements will be reflected globally, but changes made by vector operations are not! Try code below with a being an array and using ‘a=a**2’ instead of the for loop. Then try a[0]=2. def funct(a): for i in range(len(a)): a[i]=a[i]**2 print Inside function: a= , a return a=[1,2,3,4] print Outside function: a= , a funct(a) print Outside function: a= , a ...
View Full Document

{[ snackBarMessage ]}