This document contains some simple examples on data analysis and plotting. Let's load some example data from http://www.nhao.jp/~sbaar/seminar/jdata4_err0.txt
import numpy as np
from matplotlib import pyplot as plt
We could use the standard python function "open" as follows:
f = open("jdata4_err0.txt","r")
for i in f: ### Loop to print the contents of the file "jdata4_err0.txt" line by line.
print i
break ### Stops the loop after the first iteration
List = []
for i in f:
List.append(i)
List[0][0:11] ### and so on ... let's not waste anymore time on parsing data
float(List[0][0:11])*3
However, this can take a few lines and numpy offers a shorter version to dump the contents of a text file into a numerical array (genfromtxt).
data = np.genfromtxt("jdata4_err0.txt")
print data[0:4] ### prints the first four lines of the array.
Let's plot the data assuming the first column represents the horizontal axis and the second column represents the vertical axis.
#plt.figure(figsize = (10,5))
plt.plot(data[:,0], data[:,1], "-r") ## last argument defines the line style
plt.xlabel("time")
plt.ylabel("Brightness")
plt.show()
In the plot, at least two points appear to be out of order. We can see the two points better plotting the time column over it's idices.
plt.figure(figsize = (10,5))
plt.plot(data[:,0])
plt.show()
We can produce a filter that will resolv the indices of the two miss aligned points.
The next example shows how to plot a simple sinus function. Also some array properties are demonstrated.
beginn = -2.*np.pi
endd = 2.*np.pi
x = np.linspace(beginn,endd,20)
y = np.sin(x)
plt.plot(x,y,".")
plt.show()
y.mean()
y.max()
y.min()
y.std()
a = np.array([34,1,213,12,321,13])
b = np.arange(6)
print a
print b
print np.sort(a)
print np.argsort(a)
While sort() sorts the array directly from smallest to largest element, argsort() returnes the indices representing the sorted array. This means argsort() returns a method on how to sort a specific array, which can be applied to any array with the same shape.
print a[np.argsort(a)]
print b[np.argsort(a)]
textA = np.array(["cat","dog","snake","miau","rabit","pig"])
print textA[np.argsort(a)]
Following, the example data from above is sorted.
dataX, dataY = data[:,0], data[:,1]
print data.shape, dataX.shape, dataY.shape
Xsort = np.sort(dataX) ### or dataX[np.argsort[dataX]]
Ysort = dataY[np.argsort(dataX)] ### the elements of dataY are aranged in the same way dataX has been sorted.
plt.figure(figsize = (12,6))
plt.plot(dataX,dataY+0.05, label = "raw") ### dataY is offset by 0.05
plt.plot(Xsort,Ysort, label = "sorted")
plt.xlabel("time")
plt.ylabel("Amplitude")
plt.grid()
plt.xlim([Xsort.min(),Xsort.max()])
plt.legend()
plt.show()
Generating Data with Numpy
print np.zeros(5)
print np.ones((5))
print np.zeros((5,5))
print np.random.rand(5)
Let's create some 2D noise
R = np.random.rand(50,50)
plt.imshow(R)
plt.colorbar()
plt.show()
3D trigonometric funcions
I the following example, we create a 2D grid on which we spawn a 3D function. Meshgrid() creates a 2D grid for each direction (x and y).
B = 0.
E = 2.*np.pi
X = np.linspace(B,E,500)
Y = np.linspace(B,E,500)
XX, YY = np.meshgrid(X,Y)
Z = np.sin(XX)+np.cos(YY)
print X.shape ### 1D
print XX.shape ### 2D
fig = plt.figure(figsize = (7,7))
plt.plot(XX[1::25,1::25],YY[1::25,1::25],"r.") ### plots every 25th grid point of XX
plt.plot(XX[1::50,1::50],YY[1::50,1::50],"ko") ### plots every 50th grid point of XX
plt.show()
We can use the subplot function to display the arrays XX and YY, that span the grid side by side.
f, (ax1, ax2) = plt.subplots(1, 2, sharey=True, figsize = (10,5))
ax1.imshow(XX)
ax2.imshow(YY)
plt.show()
plt.imshow(Z,cmap = "spring", origin='lower')
plt.colorbar()
plt.show()
Let's determine the Minimum and it's position in the computed FOV.
print Z.min() ### Minimum Value
print np.argmin(Z, axis=0)[0] ### Minimum Y position
print np.argmin(Z, axis=1)[0] ### Minimum X position
Fig = plt.figure(figsize = (9,8))
plt.imshow(Z,cmap = "spring", origin = "lower")
plt.plot([np.argmin(Z, axis=1)[0]],
[np.argmin(Z, axis=0)[0]],
"w+", markersize = 20,
label = "minimum: "+str(round(Z.min()) ) )
plt.colorbar()
plt.legend()
plt.show()
Let's convolve the amplitude Z with some noise.
ZN = Z * np.random.rand(Z.shape[1],Z.shape[0])
Fig = plt.figure(figsize = (9,8))
plt.imshow(ZN,cmap = "spring", origin = "lower")
plt.plot([np.argmin(ZN, axis=1)[0]],
[np.argmin(ZN, axis=0)[0]],
"w+", markersize = 15,
label = "minimum of ZN: "+str(round(ZN.min(),2) ) )
plt.plot([np.argmin(Z, axis=1)[0]],
[np.argmin(Z, axis=0)[0]],
"k+", markersize = 15,
label = "minimum of Z: "+str(round(Z.min(),2) ) )
plt.colorbar()
plt.legend()
plt.show()