python 交集绘图_Python-Matplotlib:查找线图的交集

本文介绍了如何使用Python的matplotlib库找出两个非解析数据集线图的交点。通过scipy.interpolate.PiecewisePolynomial创建分段多项式函数,然后通过函数差值的根来找到交点,利用scipy.optimize.fsolve求解交点。这种方法适用于处理任意线性数据。
摘要由CSDN通过智能技术生成

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

解决方案

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

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值