English 中文(简体)
页: 1
原标题:Python - matplotlib: find intersection of lineplots

我可能有一个简单的问题,使我已经平静下来了。 是否有一种简单的办法,可以把两个被划为(非分析)数据集的交汇回平方?

详细情况,我有这样的情况:

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

这方面的数据完全是任意的。 我现在想知道,我是否在职能上有一个简单的建构,而我却把两个地块混为一谈。

我希望我表明自己,而且我也假想出一个完全明显的错误......

最佳回答

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

那么,我们就可以区分这两项职能,

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

http://docs.scipy.org/doc/scipy/vis/generated/scipy.optimize.fsolve.html#scipy-optimize-fsolve”rel=“noreferer”_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]]

第1栏是X-数值,第2栏是第一个PecewisePolynomial在x上评价的,第3栏是第二栏目PecewisePolynomial的 y-数值。

问题回答

<>Paramet> 解决办法

如果序列{x1,y1}和{x2,y2}界定了任意(x,y)曲线,而不是(x)曲线,我们需要一种分辨率的方法,以找到交叉点。 既然这样说并非完全清楚,因为“@unutbu”的解决办法在SciPy使用一个错误的推论者,我认为重新讨论这个问题可能是有益的。

import numpy as np
from numpy.linalg import norm
from scipy.optimize import fsolve
from scipy.interpolate import interp1d
import matplotlib.pyplot as plt

x1_array = np.array([1,2,3,4,6,8,9])
y1_array = np.array([4,12,7,1,6.3,8.5,12])
x2_array = np.array([1.4,2.1,3,5.9,8,9,23])
y2_array = np.array([2.3,3.1,1,3.9,8,9,11])

s1_array = np.linspace(0,1,num=len(x1_array))
s2_array = np.linspace(0,1,num=len(x2_array))

# Arguments given to interp1d:
#  - extrapolate: to make sure we don t get a fatal value error when fsolve searches
#                 beyond the bounds of [0,1]
#  - copy: use refs to the arrays
#  - assume_sorted: because s_array ( x ) increases monotonically across [0,1]
kwargs_ = dict(fill_value= extrapolate , copy=False, assume_sorted=True)
x1_interp = interp1d(s1_array,x1_array, **kwargs_)
y1_interp = interp1d(s1_array,y1_array, **kwargs_)
x2_interp = interp1d(s2_array,x2_array, **kwargs_)
y2_interp = interp1d(s2_array,y2_array, **kwargs_)
xydiff_lambda = lambda s12: (np.abs(x1_interp(s12[0])-x2_interp(s12[1])),
                             np.abs(y1_interp(s12[0])-y2_interp(s12[1])))

s12_intercept, _, ier, mesg 
    = fsolve(xydiff_lambda, [0.5, 0.3], full_output=True) 

xy1_intercept = x1_interp(s12_intercept[0]),y1_interp(s12_intercept[0])
xy2_intercept = x2_interp(s12_intercept[1]),y2_interp(s12_intercept[1])

plt.plot(x1_interp(s1_array),y1_interp(s1_array), b. , ls= - , label= x1 data )
plt.plot(x2_interp(s2_array),y2_interp(s2_array), r. , ls= - , label= x2 data )
if s12_intercept[0]>0 and s12_intercept[0]<1:
    plt.plot(*xy1_intercept, bo , ms=12, label= x1 intercept )
    plt.plot(*xy2_intercept, ro , ms=8, label= x2 intercept )
plt.legend()

print( intercept @ s1={}, s2={}
 .format(s12_intercept[0],s12_intercept[1]), 
       intercept @ xy1={}
 .format(np.array(xy1_intercept)), 
       intercept @ xy2={}
 .format(np.array(xy2_intercept)), 
       fsolve apparent success? {}: "{}"
 .format(ier==1,mesg,), 
       is intercept really good? {}
 .format(s12_intercept[0]>=0 and s12_intercept[0]<=1 
      and s12_intercept[1]>=0 and s12_intercept[1]<=1 
      and np.isclose(0,norm(xydiff_lambda(s12_intercept)))) )

返回原住者,选择最初的gues [0.5,0.3]:

intercept @ s1=0.4761904761904762, s2=0.3825944170771757
intercept @ xy1=[3.85714286 1.85714286]
intercept @ xy2=[3.85714286 1.85714286]
fsolve apparent success? True: "The solution converged."
is intercept really good? True

这种方法只发现一个交叉点:我们需要在几个初步的电离层(如“unutbu s代码”那样)中进行消化,检查其真实性,并用<代码>np.close消除重复。 请注意,fsolve 可不实地表明在收益价值ier<>code/code>中成功地发现了交叉点,这就是为什么在此进行额外核对的原因。

Here s the plot for this solution: Example solution





相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...