You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Scipy curve_fit拟合线偏移至图表顶部问题求助

问题:Scipy curve_fit拟合线偏移至图表顶部异常

我需要基于Excel文件绘制散点图及带误差的最佳拟合线,但使用Scipy的curve_fit得到的拟合线偏移至图表顶部,显示异常。已完成云盘挂载,散点图显示正常,附上代码、生成的图表及数据说明。

原代码

import matplotlib.pyplot as plt
import numpy as np
from sympy import S, symbols, printing
import scipy.optimize as sci
import pandas as pd
from pathlib import Path


#Importing all the relevant packages for the code, plotting, finding the best fit, analyzing our data and error analysis
file=pd.read_csv(r'/content/drive/MyDrive/Dataset 1(no offset part1 plate 1).csv',sep=";")
file = file.replace(r",", ".", regex=True).astype(float)
x_axis=file['Current I_A1 / A']
y_axis=file['Voltage U_B2 / V']


#Making an array of our calculated Indices of Refraction
plt.title("Hall Voltage vs Current for -10, mT B Field") #Giving our plot a relevant title that also explains what is being plotted so the graph is stand-alone
plt.xlabel("Current [A]") #Giving the x axis a label
plt.ylabel("Hall Voltage [V]") #Giving the y axis a label
plt.grid() #Giving the plot a grid.
def f(x,a,b):
    f=a*x+b
    return f #Defining our function that is going to be fitted through our data points
def g(x,a,b): #Definin the theoretical function
    g=a*x+b
    return g
plt.scatter(x_axis,y_axis, color='purple', label= 'measured') #Making a scatter plot of our data points with a Label
fit1, covariance1 = sci.curve_fit(f, x_axis, y_axis) #Using scipy making a best fit throug the data points
plt.plot(x_axis, f(x_axis,*fit1), label='Best Fit')  #Displaying the equation of best fit line in the plot #Displaying the equation of best fit line in the plot
plt.legend(loc='best') #Showing the labels belonging to both graphs
plt.show() #Showing the plot
print("n","=",round(fit1[0],4),"*","C" ,"+",abs(round(fit1[1],3))) #Printhing the equation of the best fit and giving the appropiate amount of decimals
print("delta a=",round(np.sqrt(covariance1[0][0]),4)) #Print the uncertainty of the slope of the best fit
print("delta b =",round(np.sqrt(covariance1[1][1]),4)) #Print the uncertainty of the y intercept of the best fit

异常图表

异常拟合线:拟合线偏移至图表顶部

数据说明

数据为-10mT磁场下霍尔电压与电流的测量值,包含两列:电流(Current I_A1 / A)、霍尔电压(Voltage U_B2 / V)。


解决方案

问题根源

拟合线偏移是因为curve_fit默认初始参数[1,1]与数据实际趋势(斜率为负、毫伏级量级)偏差过大,导致拟合收敛到局部最优解;同时数据处理环节未验证转换结果,可能隐藏格式错误。

修正步骤与代码

  1. 先验证数据读取结果,确保小数格式转换正确
  2. 手动指定符合数据趋势的初始拟合参数,引导curve_fit收敛到正确解
  3. 简化冗余代码,避免不必要的模块导入
import matplotlib.pyplot as plt
import numpy as np
import scipy.optimize as sci
import pandas as pd

# 读取并验证数据
file = pd.read_csv('/content/drive/MyDrive/Dataset 1(no offset part1 plate 1).csv', sep=";")
# 转换欧洲格式小数(逗号转点),并指定列类型确保转换正确
file = file.replace(',', '.', regex=True)
file = file.astype({'Current I_A1 / A': float, 'Voltage U_B2 / V': float})
x_axis = file['Current I_A1 / A']
y_axis = file['Voltage U_B2 / V']

# 打印数据前5行,确认电压为毫伏级负数
print("数据预览:")
print(file.head())

# 绘图与拟合
plt.title("-10mT磁场下霍尔电压与电流的关系")
plt.xlabel("电流 [A]")
plt.ylabel("霍尔电压 [V]")
plt.grid()

# 定义线性拟合函数
def linear_fit(x, a, b):
    return a * x + b

# 根据散点趋势指定初始参数p0:斜率为负,截距接近0
fit_params, covariance = sci.curve_fit(linear_fit, x_axis, y_axis, p0=[-0.002, 0])

plt.scatter(x_axis, y_axis, color='purple', label='测量数据')
plt.plot(x_axis, linear_fit(x_axis, *fit_params), label='最佳拟合线')
plt.legend(loc='best')
plt.show()

# 输出拟合结果与误差
print(f"拟合方程:U = {round(fit_params[0], 6)} * I + {round(fit_params[1], 6)}")
print(f"斜率误差:δa = {round(np.sqrt(covariance[0][0]), 6)}")
print(f"截距误差:δb = {round(np.sqrt(covariance[1][1]), 6)}")

关键说明

  • 验证数据是第一步:确保电压列数值为毫伏级负数,避免格式转换错误导致拟合基础数据异常
  • 初始参数引导拟合:当数据量级与默认初始值偏差较大时,手动指定p0能避免curve_fit收敛到错误的局部最优解
  • 冗余模块清理:原代码导入的sympy和Path未实际使用,可删除以简化代码

内容的提问来源于stack exchange,提问作者dutchrunner

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 11:09:50