How can I add a line of best fit for data input by the user? So far I have made a loop for collecting the data and it's length but I'm not sure how to get it to recognise these values as a string of x and y values, and it needs to be an array to do a least squares plot/best fit. I'm fairly new to coding so any help would be appreciated, thanks.
import matplotlib as plt
import numpy as np
x=[]
y=[]
for i in range(1, 20):
print('Concentration?')
x = input()
print('Absorbance?')
y = input()
plt.plot(x, y, 'o', label="Data", markersize=5)
if i == 3:
break
else:
continue
A = np.vstack([x,np.ones(len(x))]).T
print(A)
#
m, c = np.linalg.lstsq(A, y, rcond=None)[0]
plt.plot(x,m*x+c, 'r', label="Fit")
plt.show()
You need to append your inputs to the list. Then in your plot you need to calculate the points for y which I've shown in the list comprehension part.
Alternatively you could just use seaborn regplot which will handle all of this for you.
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
x=[]
y=[]
for i in range(1, 20):
print('Concentration?')
x.append(float(input()))
print('Absorbance?')
y.append(float(input()))
plt.plot(x, y, 'o', label="Data", markersize=5)
if i == 3:
break
else:
continue
A = np.vstack([x,np.ones(len(x))]).T
m, c = np.linalg.lstsq(A, y, rcond=None)[0]
plt.plot(x,[m*_+c for _ in x], 'r', label="Fit")
sns.regplot(x,y, ci=None)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.