#Week 4 Examples import numpy as np import matplotlib.pyplot as plt #Defining a simple 2D array A = np.array([[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15]]) #If I print A: # # out: array([[ 1, 2, 3, 4, 5] # [6, 7, 8, 9, 10] # [11,12,13,14,15]]) #Using existing arrays and stacking them a1 = [1,2,3,4,5] a2 = [2,3,4,5,6] a3 = [3,4,5,6,7] two_d = np.vstack((a1,a2,a3)) # If I print two_d: # # out: array([[1,2,3,4,5] # [2,3,4,5,6] # [3,4,5,6,7]]) #Can use hstack if you have columns rather than rows col1 = np.array([[1],[2],[3]]) col2 = np.array([[5],[7],[1]]) col3 = np.array([[9],[4],[6]]) stacked = np.hstack((col1,col2,col3)) #Output is # array([[1,2,3] # [5,7,1] # [9,4,6]]) # # ########################################################## #Plotting Stuff #Generate some fake data to play around with x = np.arange(100) y = x**2 y2 = y + 550 * np.random.normal(size=x.shape) #random data in a normal distribution around the original line y=x**2 #simple plot: plt.plot(x,y2) #Plot with default settings plt.title('Most simple plot with default settings') plt.show() #Labeled Plot: plt.figure() #create a new figure (like a new blank canvas to plot on, so it doesn't mess with the previous plot) plt.plot(x,y2,'r+',label='Data Points') #using red plus symbols, and creating a label for the legend plt.legend() #can use arg (loc=1), with integer 1-4 to specify which corner legend is in plt.title('Plot with Label+legend') plt.show() #Error-Bar plot: y_error = y2/np.random.randint(1,20) ''' Here I generate an array of "errors" for our fake data from above. This is pretty much arbritrary- but generally with measurements of at least a 1 sigma detection, the error bars' lengths are anywhere up to 1/3 the value at the point. The exact thing I do is in the yerr array, each value is the value of y2 at that point divided by a random integer 1-20. ''' plt.figure() plt.errorbar(x,y2,yerr=y_error,fmt='s',c='r',label='Data') plt.title('Error bar Plot') plt.legend(loc=2) plt.show() #i.e., we use the yerr argument to specify the array with the error for each point #There is also an xerr argument if you have an array of uncertainties in x as well plt.figure() #Of course, you can plot multiple data sets on the same plot: y3 = x**2 + 2000 y4 = y3 + 335 * np.random.normal(size=x.shape) plt.plot(x,y2,'r+',label='Set 1') plt.plot(x,y4, 'b^', label='Set2') plt.title('multiple data sets') plt.legend(loc=2) plt.show() #Creating a Histogram ''' Histograms are useful because they allow you to see the distribution of a dataset. Often times if you look at independently collected data points from sample, the means will follow a normal distribution. (our fake data does as well, by construction). ''' #Generate some Fake Data mu = 200 sigma = 25 x = mu + sigma*np.random.randn(10000) plt.figure() plt.hist(x, 20, normed=1, histtype='stepfilled', facecolor='g', alpha=0.75) plt.title('A histogram') plt.show() #MISC Plotting #plt.annotate('text', xy=(1,3)) #put in coords to put text on graph