1.画二维关系图
例如以下数据:
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif']=['SimHei']
plt.rcParams['axes.unicode_minus'] = False
plt.title("无水乙醇与正丙醇混合液的浓度与折射率")
plt.xlim(xmax=110, xmin=0)
plt.ylim(ymax=1.3850, ymin=1.3550)
plt.xlabel("正丙醇的摩尔百分数(%)")
plt.ylabel("折射率")
plt.plot([0.0, 7.70, 16.0, 24.6, 33.7, 43.2, 53.3, 63.8, 75.3, 87.3, 100.00],
[1.3592, 1.3619, 1.3642, 1.3668, 1.3691, 1.3715, 1.3740, 1.3764, 1.3789, 1.3812, 1.3839], 'ro')
plt.show()
2.求曲线的拟合公式
例如:根据上述1的数据拟合公式
线性公式拟合
import numpy as np
Y = [0.0, 7.70, 16.0, 24.6, 33.7, 43.2, 53.3, 63.8, 75.3, 87.3, 100.00]
X = [1.3592, 1.3619, 1.3642, 1.3668, 1.3691, 1.3715, 1.3740, 1.3764, 1.3789, 1.3812, 1.3839]
z1 = np.polyfit(X, Y, 1)
p1 = np.poly1d(z1)
print(z1)
print(p1)
#[ 4069.10408341 -5535.09820153]
#4069 x - 5535
二次多项式拟合
import numpy as np
def polyfit(x, y, degree):
results = {}
coeffs = np.polyfit(x, y, degree)
results['polynomial'] = coeffs.tolist()
# r-squared
p = np.poly1d(coeffs)
# fit values, and mean
yhat = p(x) # or [p(z) for z in x]
ybar = np.sum(y) / len(y) # or sum(y)/len(y)
ssreg = np.sum((yhat - ybar) ** 2) # or sum([ (yihat - ybar)**2 for yihat in yhat])
sstot = np.sum((y - ybar) ** 2) # or sum([ (yi - ybar)**2 for yi in y])
results['determination'] = ssreg / sstot # 准确率
return results
z1 = polyfit(X, Y, 2)
print(z1)
#结果依次为 x^2 x^1 x^0 的系数
#{'polynomial': [44925.124426109105, -119165.27286295866, 78973.45552795619], 'determination': 0.9999011699884925}
对数函数拟合
from scipy import log
from scipy.optimize import curve_fit
def func(x, a, b):
y = a * log(x) + b
return y
def polyfit(x, y, degree):
results = {}
# coeffs = numpy.polyfit(x, y, degree)
popt, pcov = curve_fit(func, x, y)
results['polynomial'] = popt
# r-squared
yhat = func(x, popt[0], popt[1]) # or [p(z) for z in x]
ybar = np.sum(y) / len(y) # or sum(y)/len(y)
ssreg = np.sum((yhat - ybar) ** 2) # or sum([ (yihat - ybar)**2 for yihat in yhat])
sstot = np.sum((y - ybar) ** 2) # or sum([ (yi - ybar)**2 for yi in y])
results['determination'] = ssreg / sstot
return results
z1 = polyfit(Y, X, 2)
print(z1)
#{'polynomial': array([1., 1.]), 'determination': inf}
于是对于以下实验数据,我们就可以带公式求出未知数啦!