Find two points/derivatives on curves between which the line is straight/constant
我正在绘制 x 和 y 点。这导致了一条曲线,这条线首先弯曲,然后在一个点之后变成直线,一段时间后它再次弯曲。我想找回这两点。虽然 x 是线性的并且 y 是针对 x 绘制的,但 y 不是线性依赖于 x。
我尝试使用 matplotlib 绘制和 numpy 多项式函数,目前正在研究样条曲线,但似乎对于这些
您的数据很嘈杂,因此您不能使用简单的数值导数。相反,正如您可能已经发现的那样,您应该使用样条曲线拟合它,然后检查样条曲线的曲率。
关闭这个答案,您可以拟合样条曲线并计算二阶导数(曲率),如下所示:
1 2 3 4 5 6 7 8 9 10 11 | import numpy as np import matplotlib.pyplot as plt from scipy.interpolate import UnivariateSpline x = file['n'] y = file['Ds/2'] y_spline = UnivariateSpline(x, y) x_range = np.linspace(x[0], x[-1], 1000) # or could use x_range = x y_spline_deriv = y_spl.derivative(n=2) curvature = y_spline_deriv(x_range) |
然后你可以像这样找到直线区域的开始和结束:
1 2 3 4 5 | straight_points = np.where(curvature.abs() <= 0.1)[0] # pick your threshold start_idx = straight_points[0] end_idx = straight_points[-1] start_x = x_range[start_idx] end_x = x_range[end_idx] |
或者,如果您主要对找到曲线的最平坦部分感兴趣(如图所示),您可以尝试计算一阶导数,然后找到斜率在最小斜率的一小部分范围内的区域数据中的任何位置。在这种情况下,只需在上面的代码中替换