Python-Matplotlib:查找线图的交集 [英] Python - matplotlib: find intersection of lineplots

查看:313
本文介绍了Python-Matplotlib:查找线图的交集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个可能很简单的问题,这使我已经安静了一段时间.有没有一种简单的方法可以在python matplotlib中返回两个绘制的(非分析性)数据集的交集?

I have a probably simple question, that keeps me going already for quiet a while. Is there a simple way to return the intersection of two plotted (non-analytical) datasets in python matplotlib ?

为了详细说明,我有这样的内容:

For elaboration, I have something like this:

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-')

此示例中的数据完全是任意的.现在,我想知道是否有一个简单的内置函数会丢失,该函数会向我返回两个图之间的精确交点.

The data in this example is totaly arbitrary. I would now like to know if there is a simple build in function that I keep missing, that returns me the precise intersections between the two plots.

希望我能说清楚自己的意思,而且我也没有错过任何显而易见的事情……

Hope I made myself clear, and also that I didnt miss something totaly obvious...

推荐答案

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

We could use scipy.interpolate.PiecewisePolynomial to create functions which are defined by your piecewise-linear data.

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

然后我们可以利用这两个功能的差异,

We could then take the difference of these two functions,

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

并使用进行优化. f 查找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值.

The first column is the x-value, the second column is the y-value of the first PiecewisePolynomial evaluated at x, and the third column is the y-value for the second PiecewisePolynomial.

这篇关于Python-Matplotlib:查找线图的交集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆