找到水平线穿过相应 Y 轴值的 X 轴数据点

find X-axis data points where horizontal line passes through on respective Y-axis value

我在 x-axis 上有一个 [1,2,3,4,5] 个数据点,在 y-axis 上有其各自的值,例如 [10,15,10,10,20]

通常通过给定的 x-axis 数据点找到 y-axis 的值点 像 y=f(x),我检查了这个,我们可以通过 interpolation 使用 numpy 来实现。但是我没有找到如何通过给定的 y 轴值插入 x 轴。作为每个附加屏幕我想找到相应的 x 轴值,其中线 12 交叉..
所以我期待结果类似于 [1, 1.x, 2, 2.x, 3, 4, 4.x, 5, 5.x] on x-axis

如果将 interp1d(x,y) 更改为 interp1d(y,x),则表示 x 是 y 的函数。

请注意,如果 f(x) 不是唯一的,您可能会遇到意外或未定义的行为。

如果是平滑曲线,可以用InterpolatedUnivariateSpline

import numpy as np
from scipy import interpolate

x = np.linspace(0, 20, 100)
y = np.sin(x + 0.1)

y0 = 0.3
spline = interpolate.InterpolatedUnivariateSpline(x, y - y0)

xp = spline.roots()

剧情如下:

pl.plot(x, y)
pl.axhline(0.3, color="black", linestyle="dashed")
pl.vlines(xp, 0, 0.3, color="gray", linestyle="dotted")

如果你想要线性插值:

x = np.linspace(0, 20, 20)
y = np.sin(x + 0.1)
y0 = 0.3
y_offset = y - y0
pos = np.where((y_offset[1:] * y_offset[:-1]) <= 0)[0]

x1 = x[pos]
x2 = x[pos+1]
y1 = y[pos]
y2 = y[pos+1]

xp = (y0 - y1) / (y2 - y1) * (x2 - x1) + x1