给定x值,获取曲线的y值
给定一个 Line2D
对象,这是用 pyplot
的 plot
函数生成的,我想知道在某个特定的 x
值下对应的 y
坐标。例如,如果
import numpy as np
import matplotlib.pyplot as plt
x = np.array([1.0, 4.0, 9.0, 16.0])
y = np.array([1.0, 2.0, 3.0, 4.0])
line = plt.plot(x, y)[0]
那么
def get_y(line, x):
...
## This should print something close to 2.0
print get_y(line, 2) ** 2
我尝试使用 path = line.get_path()
,然后进行插值,但结果并没有像我预期的那样工作。我觉得应该有一种标准的方法来做到这一点……
2 个回答
0
也许 numpy.interp(x, xp, fp, left=None, right=None)
可以帮到你。你可以查看这个链接了解更多信息:http://docs.scipy.org/doc/numpy/reference/generated/numpy.interp.html
1
如果我理解得没错,你想知道在一条线段ab
上,一个点p
的高度y
。
假设这条线是无限长的,我们可以这样来计算。
首先,计算这条线的斜率:
height = lineEndY - lineStartY #calculate the line "height"
lenghtX = abs(lineStartX - lineEndX) #calculate the length of line along the X axis
slope = height / lengthX; #calculate the "slope" by deviding length of x by height
result = x * slope; #calculate the x approx height on the line