Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - matplotlib: find intersection of lineplots

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...

like image 561
Christian Avatar asked Nov 11 '11 13:11

Christian


1 Answers

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)

and use optimize.fsolve to find the roots of 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))))

yields

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

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.

like image 150
unutbu Avatar answered Oct 18 '22 05:10

unutbu