[英]How can I plot user input data onto a graph with a line of best fit?
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.
到目前为止,我已经制作了一个循环来收集数据及其长度,但我不确定如何让它将这些值识别为 x 和 y 值的字符串,并且它需要是一个数组来做最小二乘图/最合适。 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.您需要将 append 输入到列表中。 Then in your plot you need to calculate the points for y which I've shown in the list comprehension part.
然后在您的 plot 中,您需要计算我在列表理解部分中显示的 y 点。
Alternatively you could just use seaborn regplot which will handle all of this for you.或者,您可以只使用 seaborn regplot 它将为您处理所有这些。
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.