graph.py
#!/usr/bin/env python
'''
semilog.py
Eric Ayars
10/4/16
Graphing demonstration showing how to create semi-log
plots and curve fits relevant to Advanced Lab.
'''
from pylab import *
from scipy.optimize import curve_fit
# Data (Made-up, with realistic error)
t = array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25])
N = array([ 90., 64., 54., 57., 52., 51., 32., 35., 32., 26., 23., 22., 18., 9., 9., 9., 11., 5., 5., 4., 2., 2., 4., 3., 3.])
time = linspace(0,25,100)
# Linear plot, with curve fits
errorbar(t, N, yerr=sqrt(N), fmt='bo')
title('Radioactive Decay')
xlabel('Time (minutes)')
ylabel('Counts')
# Equation for curve fit
def decay(t, A, B):
return A*exp(-t/B)
guess = [100,5] # Doesn't have to be a particulary good guess, usually.
params, cov = curve_fit(decay, t, N, guess)
print('A = %0.3f, B = %0.3f' % (params[0], params[1]))
print('dA = %0.3f, dB = %0.3f' % (sqrt(cov[0,0]), sqrt(cov[1,1])))
plot(time, decay(time, params[0], params[1]), 'g-')
# Add a legend
legend(['Data', 'Curve Fit'], loc='upper right')
# add annotations
text(19,65, r'$N = N_o e^{-t/\tau}$')
text(19,60, r'$N_o = %0.2f \pm %0.2f$' %(params[0], sqrt(cov[0,0])))
text(19,55, r'$\tau = %0.2f \pm %0.2f$' %(params[1], sqrt(cov[1,1])))
# limit y range on display
#ylim(0,100)
# If you want to save the graph...
#savefig('semilog_plot.pdf')
show()
Generated by GNU Enscript 1.6.6.