【问题标题】:How to find intersection point between plot and a straight line [duplicate]如何找到绘图和直线之间的交点[重复]
【发布时间】:2019-06-11 05:13:06
【问题描述】:

您好,我需要找到 2 个地块之间的交点,一个是弯曲的,另一个是直线,如下图所述

plt.figure()
plt.plot(lst)
plt.plot([x1, x2], [y1, y2], marker='o')
plt.show()

有什么直接的方法吗

【问题讨论】:

标签: python matplotlib geometry


【解决方案1】:

我怀疑您遇到了数学问题,而不是代码问题。

数学

交点是,其中f1、f2由“定义”

为什么要在“已定义”周围加上引号?好吧,这定义了输入采样点上的函数,但不能保证交集就是其中之一。因此,您需要以某种方式猜测采样点之间的函数等于什么;这是一个插值的问题,它可以是任何地方,从“微不足道”到“写一篇关于最佳方法的博士学位”。

我假设在您的情况下可以使用线性插值法(在数据点之间绘制直线)。在这种情况下,只要 在这些数据点之间更改符号,就会在连续数据点之间的段中存在一个交点。

代码

在您的确切情况下,函数之一是常量:,这简化了解决方案。 (如果不是这种情况,您将不得不沿着每条曲线的各段行走并检查交叉点;这可以在线性时间(两个数组长度之和)内完成,但需要更多编码。)

import matplotlib.pyplot as plt
import numpy as np


def find_intersections(x, y, C):
    # Contains numpy indexing tricks that can be hard to reproduce
    # in the case where both functions are non-constants
    ii, = np.nonzero((y[1:]-C)*(y[:-1]-C) < 0.)  # intersection indices
    x_intersections = x[ii] + (C - y[ii])/(y[1+ii] - y[ii])*(x[1+ii] - x[ii])
    y_intersections = C * np.ones(len(ii))
    return x_intersections, y_intersections


# parabolic data for example
x1 = np.linspace(-2., 2)
y1 = x1 ** 2

C = 2.0
x2 = np.asarray([min(x1), max(x1)])
y2 = np.asarray([C, C])


xint, yint = find_intersections(x1, y1, C)

plt.figure()
plt.plot(x1, y1)
plt.plot(x2, y2)
plt.plot(xint, yint, 'ro')
plt.show()

【讨论】:

    【解决方案2】:

    试试这个

    import numpy as np
    n = len(lst)
    y = np.linspace(y1, y2, n)
    close = np.argwhere(np.isclose(lst, y, rtol = 1/n)
    print(close)
    

    如有必要,请使用相对容差rtol

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-16
      • 2017-08-18
      相关资源
      最近更新 更多