#numpy for mathematical calculations
import numpy as np
#matplotlib for plotting
import matplotlib.pyplot as plt
#scipy.optimize for linear and non-linear regression
from scipy.optimize import curve_fit
def f (x, a, b):
return a*x+b
#Longest Spring Data
x, F = np.loadtxt('/Applications/Stuff/Coding/Python/Physics/Data/Spring Constant Experiment - Longest.csv', delimiter = ',', skiprows= 1, unpack = True)
#2nd Longest Spring Data
x1, F1 = np.loadtxt('/Applications/Stuff/Coding/Python/Physics/Data/Spring Constant Experiment - 2nd Longest.csv', delimiter = ',', skiprows= 1, unpack = True)
#3rd Longest Spring Data
x2, F2 = np.loadtxt('/Applications/Stuff/Coding/Python/Physics/Data/Spring Constant Experiment - 3rd Longest.csv', delimiter = ',', skiprows= 1, unpack = True)
#4th Longest Spring Data
x3, F3 = np.loadtxt('/Applications/Stuff/Coding/Python/Physics/Data/Spring Constant Experiment - 4th Longest.csv', delimiter = ',', skiprows= 1, unpack = True)
#Longest + 2nd Longest Spring Data
x4, F4 = np.loadtxt('/Applications/Stuff/Coding/Python/Physics/Data/Spring Constant Experiment - Longest + 2nd Longest.csv', delimiter = ',', skiprows= 1, unpack = True)
#normalize (this step is specific to this dataset)
Rnorm = x/x[0]
Rnorm1 = x1/x1[0]
Rnorm2 = x2/x2[0]
Rnorm3 = x3/x3[0]
Rnorm4 = x4/x4[0]
#Slope and Y-Intercept
popt1 , pcov1 = curve_fit(f, x, F)
popt2 , pcov2 = curve_fit(f, x1, F1)
popt3 , pcov3 = curve_fit(f, x2, F2)
popt4 , pcov4 = curve_fit(f, x3, F3)
popt5 , pcov5 = curve_fit(f, x4, F4)
#Fitting Lines
x_fit = np.arange(0,40, 0.1)
y_fit = f(x_fit, popt1[0], popt1[1])
x_fit1 = np.arange(0,40, 0.1)
y_fit1 = f(x_fit1, popt2[0], popt2[1])
x_fit2 = np.arange(0,40, 0.1)
y_fit2 = f(x_fit2, popt3[0], popt3[1])
x_fit3 = np.arange(0,40, 0.1)
y_fit3 = f(x_fit3, popt4[0], popt4[1])
x_fit4 = np.arange(0,40, 0.1)
y_fit4 = f(x_fit4, popt5[0], popt5[1])
#Uncertainty
plt.errorbar(x, F, xerr = 0.5, yerr = 0.98, fmt='o',color = 'royalblue', markersize = 5.5, label = 'Longest Spring')
plt.errorbar(x1, F1, xerr = 0.5, yerr = 0.98, fmt='o',color = 'red', markersize = 5.5, label = '2nd Longest Spring')
plt.errorbar(x2, F2, xerr = 0.5, yerr = 0.98, fmt='o',color = 'green', markersize = 5.5, label = '3rd Longest Spring')
plt.errorbar(x3, F3, xerr = 0.5, yerr = 0.98, fmt='o',color = 'goldenrod', markersize = 5.5, label = '4th Longest Spring')
plt.errorbar(x4, F4, xerr = 0.5, yerr = 0.98, fmt='o',color = 'black', markersize = 5.5, label = 'Longest + 2nd Longest Spring')
#quick plot to visualize the data
plt.plot(x_fit,y_fit, color=('cornflowerblue'))
plt.plot(x_fit1,y_fit1, color=('orange'))
plt.plot(x_fit2,y_fit2, color=('limegreen'))
plt.plot(x_fit3,y_fit3, color=('gold'))
plt.plot(x_fit4,y_fit4, color=('grey'))
#add labels, title, and legend
plt.title('Spring Constant Experiment')
plt.xlabel('Length(cm)')
plt.ylabel('Force(N)')
plt.legend()
<matplotlib.legend.Legend at 0x1575548d0>
Thank you to my physics teacher for teaching me this stuff!