PHYSICS 2235

### PHYSICS 2235 Lab 07

Useful reference: matplotlib

#### Exercise 1: Multiple graphs on the same plot

In some cases you will need to plot multiple data points on the same plot


import numpy as np
import matplotlib.pyplot as plt

def f1(t):
return t

def f2(t):
return t**2

def f3(t):
return t**3

t = np.arange(0., 5., 0.2)

# red dashes, blue squares and green triangle
plt.plot(t, t, 'r--')
plt.plot(t,f2(t), 'bs')
plt.plot(t,f3(t), 'g^')

plt.ylabel('functions of t')
plt.xlabel('t')
plt.title('Some Functions')
plt.show()

Now which plot is which function?
To be able to to save that information on the plot you need legends.
To have legends on your plot replace the lines in the previous code
plt.plot(t, t, 'r--')
plt.plot(t,f2(t), 'bs')
plt.plot(t,f3(t), 'g^')

with
# red dashes, blue squares and green triangles
plt.plot(t, t, 'r--', label='linear')
plt.plot(t,f2(t), 'bs', label='to the power 2')
plt.plot(t,f3(t), 'go', label='to the power 3')

plt.legend()


• Add another function f4(x) that plots x to the power of 4 to the same plot. Make sure you have the correct legends for f4(x).

#### Exercise 2: Log scale

It is often useful to make plots in logarithmic scale. For example:
your data contains a wide range of numbers from less than unity to several thounsands.

import numpy as np
import matplotlib.pyplot as plt

tau = 20
N0=8200
t = np.linspace(0, 180, 128)
N = N0 * np.exp(-t/tau)

plt.semilogy(t, N, 'bs')
plt.ylabel('log(N)')
plt.xlabel(' t')
plt.show()



make another subplot without the log-scale. (using plot). How does the two compare?

#### Exercise 3: reading in a file

Suppose you are trying to plot the following columns.

time (s)    position (m)    uncertainty (m)
0.0            0.0             0.04
0.5            1.3             0.12
1.0            5.1             0.2
1.5           10.9             0.3
2.0           18.9             0.4
2.5           28.7             0.4
3.0           40.3             0.5
3.5           53.1             0.6
4.0           67.5             0.6
4.5           82.3             0.6
5.0           97.6             0.7
5.5          113.8             0.7
6.0          131.2             0.7
6.5          148.5             0.7
7.0          166.2             0.7
7.5          184.2             0.7
8.0          201.6             0.7
8.5          220.1             0.7
9.0          238.3             0.7
9.5          256.5             0.7
10.0          275.6             0.8

You probably noticed that feeding these columns by hand to arrays is quite limited.
• you could easily fill the wrong number or miss an element.
The best way to do this is to create a data file that contain the data points.
Simply copy and paste the following lines in a data file called MotionData.txt
• use the following line to read in the MotionData.txt file and assign the read in values to time, distance, and the error in distance variables.
import numpy as np
t, d, dy = np.loadtxt("MotionData.txt",
skiprows=1 , unpack=True)

• now plot time (t) on the x-axis and distance (d) on the y-axis, the errors on the distance to be dy.

A useful command you could use if you don't want to read your whole file. In this case only the first two columns.
import numpy as np
x, y = np.loadtxt("MotionData.txt", skiprows=1 ,usecols = (0,1), unpack=True)

explaining more on loadtxt command options

suppose the data you are using is saved in an Excel sheet.
data point,time (sec),height (mm),uncertainty (mm)
0,0,180,3.5
1,0.5,182,4.5
2,1,178,4
3,1.5,165,5.5
4,2,160,2.5
5,2.5,148,3
6,3,136,2.5
7,3.5,120,3
8,4,99,4
9,4.5,83,2.5
10,5,55,3.6
11,5.5,35,1.75
12,6,5,0.75


copy and paste this file into a file called MyExcel.csv
Note that since the separator between columns here is NOT white space or tab you would need the following command.
import numpy as np
t, h = np.loadtxt("MyExcel.csv",
skiprows=1 ,usecols = (1,2),unpack=True, delimiter=',')

which contains the delimiter option to ',' that separates the columns in this file. Try it.

#### Exercise 4: writing out a file

To output a file you would need to use savetxt which is the counterpart of loadtxt.
savetxt(filename, array, fmt="%0.18e", delimiter=" ", newline="\n",

For example:
import numpy as np
x, y, err = np.loadtxt("MotionData.txt", skiprows=1 , unpack=True)
np.savetxt('MotionDataOut.txt',np.c_[x,y], fmt='%1.1f' )

explaining line

#### Problem 1

A simple harmonic oscillator consists of a block with mass m. A general solution for the motion of the block is given by.

x(t) = C cos(wt + \phi)

where C is the amplitude and phi is the phase. Create a plot harmx.png that contains two subplots.

• The first subplot contain the block oscillating with different amplitudes:
Plot a(x) = C*Cos(Wx+Phi) vs. x[0-2*pi]  C,W,Phi (1.0 , 1.0, 0)
Plot b(x) = C*Cos(Wx+Phi) vs. x[0-2*pi]  C,W,Phi (2.0 , 1.0, 0)
Plot c(x) = C*Cos(Wx+Phi) vs. x[0-2*pi]  C,W,Phi (3.0 , 1.0, 0)


• Second subplot contain the block oscillate with different phase.
plot d(x) = C*Cos(Wx+Phi) vs. x[0-2*pi]  C,W,Phi (1.0 , 1.0, 0)
plot e(x) = C*Cos(Wx+Phi) vs. x[0-2*pi]  C,W,Phi (1.0 , 1.0, pi)
plot f(x) = C*Cos(Wx+Phi) vs. x[0-2*pi]  C,W,Phi (1.0 , 1.0, pi/2)

• Make sure functions are plotted with different markers and color.
• Add a title for each plot
• Add the line plt.tight_layout() before saving your figure. This will help your title not to overlap with the axis of the first subplot.
• Add a legend for each plot that has the function name a(x), ...etc
• Make sure the legend is not masking your graph.
• Make sure you have enough points that your curve is smooth.

submit your code Harmonic.py .

#### Problem 2

In this assignment you will submit a figure with two subplots.

#### Part1 : The first subplot

Open the data file
gaussianData.txt The columns are x , y , and the error in y for a given data set.
• Plot the y vs. x including the error in y.
• Plot the data points in red and the error in black
• Add the title of the plot to be "normal distributions"
• The normal distribution, often called the Gaussian distribution is given as:
P(x;\mu;\sigma) = \frac{1}{\sqrt{2 \pi \sigma^{2}}} e^{\frac{-(x-\mu)^2}{2\sigma^2}}

where p is the probability of x, mu is the average and sigma is the standard deviation.
• write a function norm that takes x,mu, and sigma as input and returns the probability.

On the same plot as the data you just plotted.

• use the function to plot the normal distribution for x in the range from (-5 to +5 ) for mu =0 and sigma=1, make sure to have enough points that the function is smooth. Use a blue line to represent the function.
• Plot the normal distribution with mu=2 and sigma=1 using the green line. Make sure to have enough points that the function is smooth.
• Plot the normal distribution with mu=0 and sigma=2 using the dashed red line. Make sure to have enough points that the function is smooth.
• Make sure you have a legend that is not on top of your plots.
• The legend should say "data" for the points and the mu and the sigma values for the functions. i.e. mu=0 sigma=1
• Which distribution represent the data best. Write the answer in your code as a comment.

#### Part2: The second subplot

• Plot the normal distribution for x in the range from (-5 to +5 ) in log scale for mu =0 and sigma=1, make sure to have enough points that the function is smooth. Use a blue line to represent the function.
• Add a title to your plot normal distribution in log scale
• Add a legend that includes the mu and sigma values.
• Add the line plt.tight_layout() before saving your figure. This will help your title not to overlap with the axis of the first subplot.
submit your code and the plot as Gaussian.py and gauss123.png

#### Problem 3 (NOT A BONUS)

Read in the file corsika.txt write out to a file called "mycorsikaout.csv". The output file should not include a header and should only include the first interaction x1 and the xmax (the fourth and the sixth) columns. The columns need to be separated by a comma. Read the header of the file to make sure you are reading the correct columns. Submit a file called Outfile.py and your output file mycorsikaout.csv

Back to main Physics 2235 page