import numpy as np
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt

# 读取数据
data = np.genfromtxt('10K 热敏电阻对照表（25°为基准）.csv', delimiter=',', skip_header=1,
                     usecols=(0, 2), names=['Temperature', 'Rnor'])
# 提取温度和Rnor数据
temperature = data['Temperature']
r_nor = data['Rnor']


# 定义拟合函数，这里采用二次函数作为示例
def fit_function(x, a, b, c):
    return a * x ** 2 + b * x + c


# 进行曲线拟合
p0 = [1, 1, 1]  # 初始猜测值
popt, pcov = curve_fit(fit_function, temperature, r_nor, p0=p0)

# 生成用于绘图的拟合数据
x_fit = np.linspace(-30, 300, 400)
y_fit = fit_function(x_fit, *popt)

# 绘制原始数据和拟合曲线
plt.scatter(temperature, r_nor, label='Original Data')
plt.plot(x_fit, y_fit, 'r-', label='Fitted Curve')
plt.xlabel('Temperature (°C)')
plt.ylabel('Rnor (k Ohms)')
plt.title('Thermistor Resistance vs Temperature Fitting')
plt.legend()
plt.grid(True)
plt.show()