Python-matplotlib : find intersection of lineplots

标签 python matplotlib intersection

我有一个可能很简单的问题,它让我已经安静了一会儿。有没有一种简单的方法可以在 python matplotlib 中返回两个绘制(非分析)数据集的交集?

为了详细说明,我有这样的东西:

x=[1.4,2.1,3,5.9,8,9,23]
y=[2.3,3.1,1,3.9,8,9,11]
x1=[1,2,3,4,6,8,9]
y1=[4,12,7,1,6.3,8.5,12]
plot(x1,y1,'k-',x,y,'b-')

此示例中的数据完全是任意的。我现在想知道是否有一个我一直缺少的简单内置函数,它会返回两个图之间的精确交点。

希望我说清楚了,也希望我没有遗漏一些非常明显的东西......

最佳答案

我们可以使用 scipy.interpolate.PiecewisePolynomial 来创建由分段线性数据定义的函数。

p1=interpolate.PiecewisePolynomial(x1,y1[:,np.newaxis])
p2=interpolate.PiecewisePolynomial(x2,y2[:,np.newaxis])

然后我们可以取这两个函数的不同,

def pdiff(x):
    return p1(x)-p2(x)

并使用optimize.fsolve找到 pdiff 的根:

import scipy.interpolate as interpolate
import scipy.optimize as optimize
import numpy as np

x1=np.array([1.4,2.1,3,5.9,8,9,23])
y1=np.array([2.3,3.1,1,3.9,8,9,11])
x2=np.array([1,2,3,4,6,8,9])
y2=np.array([4,12,7,1,6.3,8.5,12])    

p1=interpolate.PiecewisePolynomial(x1,y1[:,np.newaxis])
p2=interpolate.PiecewisePolynomial(x2,y2[:,np.newaxis])

def pdiff(x):
    return p1(x)-p2(x)

xs=np.r_[x1,x2]
xs.sort()
x_min=xs.min()
x_max=xs.max()
x_mid=xs[:-1]+np.diff(xs)/2
roots=set()
for val in x_mid:
    root,infodict,ier,mesg = optimize.fsolve(pdiff,val,full_output=True)
    # ier==1 indicates a root has been found
    if ier==1 and x_min<root<x_max:
        roots.add(root[0])
roots=list(roots)        
print(np.column_stack((roots,p1(roots),p2(roots))))

产量

[[ 3.85714286  1.85714286  1.85714286]
 [ 4.60606061  2.60606061  2.60606061]]

第一列是 x 值,第二列是在 x 处计算的第一个 PiecewisePolynomial 的 y 值,第三列是第二个 PiecewisePolynomial 的 y 值。

关于Python-matplotlib : find intersection of lineplots,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8094374/

相关文章:

python - matplotlib 中有没有办法检查当前显示的轴区域中有哪些艺术家?

python - 图例在保存时被切断 - Matplotlib

python - 使用 Pandas 和 Scatter_Matrix 将不会显示

c# - 查找两个整数范围之间的重叠区域

path - 铯路径到地形 : line connecting 2 points goes under the terrain

python - 在 Mongo 中使用多个条件进行过滤

python - 为 n 种不同类型创建笛卡尔积

python - 如何在 FreeBSD 中默认设置 Python 版本?

python - 为列值的唯一组合创建 ID 号

python - 删除列表中的重复项