【问题标题】:how can I find intersection of multiple lines with a curve?如何找到多条线与曲线的交点?
【发布时间】:2020-07-08 09:24:25
【问题描述】:

我有一个包含 x 和 y 的文件。对于从 y 轴通过的每条线,我可以找到交点,但我希望有一种自动方法来找到从 y 轴通过的一堆线的交点,如下图所示:

透视结果

我为逐个查找交叉点而编写的代码如下:

import numpy as np
import matplotlib.pyplot as plt
with open('txtfile1.out', 'r') as f:
    lines = f.readlines()
    x = [float(line.split()[0]) for line in lines]
    y = [float(line.split()[1]) for line in lines]
xx = []
for i in range(1,len(x)):
    if (y[i] > 0 and y[i-1] < 0) or (y[i] < 0 and y[i-1] > 0):
        xx.append((x[i]+x[i-1])/2)

yx = [0 for _ in range(len(xx))]
plt.plot(x,y)
plt.plot(xx,yx, color="C2", marker="o", ls="", ms=10)

我拥有的东西

当前结果

【问题讨论】:

  • 两个数字相同
  • @TimStack 是的,但是在其中一个中,我需要有实线与多条直线虚线的交点,而我可以编写代码以逐个获取交点。
  • @TimStack 现在你可以看到不同之处了,你上传的图片是对的
  • 你知道直线的y值吗?它们总是一样吗?它们是否存储在另一个文件中?在已经存在的循环中添加第二个 for 循环可能是一种解决方案。
  • @TobiasBrösamle 可以根据我的情况任意定义作为直线虚线的 y 值。但我想过用这种方式来定义它们divider = np.arange(min(y),max(y),100)

标签: python numpy matplotlib


【解决方案1】:

您可以尝试设置一个额外的循环来检查您输入的多个交集值,并使用字典来保存与交集值作为键的匹配列表。从理论上讲,这应该将您想要的 y 的所有交点绘制到同一个图中

import numpy as np
import matplotlib.pyplot as plt
with open('txtfile1.out', 'r') as f:
    lines = f.readlines()
    x = [float(line.split()[0]) for line in lines]
    y = [float(line.split()[1]) for line in lines]
intersections = [0, -20, 10]
intersection_matches = {intersection: [] for intersection in intersections}
# or just define directly: intersection_matches ={ 0: [] , -20: [], 10: [] }
for i in range(1, len(x)):
  for intersection, xx in intersection_matches.items():
    if (y[i] > intersection and y[i-1] < intersection or (y[i] < intersection and y[i-1] > intersection)):
       xx.append((x[i]+x[i-1])/2)

plt.plot(x,y)
for intersection, xx in intersection_matches.items():
    yx = [intersection] * len(xx)
    plt.plot(xx, yx, color="C2", marker="o", ls="", ms=10)

【讨论】:

    【解决方案2】:
    import numpy as np
    import matplotlib.pyplot as plt
    with open('txtfile1.out', 'r') as f:
        lines = f.readlines()
        x = [float(line.split()[0]) for line in lines]
        y = [float(line.split()[1]) for line in lines]
    xx = []
    treshold = #what ever you want
    for i in range(1,len(x)):
        if (y[i] > treshold and y[i-1] < treshold) or (y[i] < treshold and y[i-1] > treshold):
            xx.append((x[i]+x[i-1])/2)
    
    yx = [treshold for _ in range(len(xx))]
    plt.plot(x,y)
    plt.plot(xx,yx, color="C2", marker="o", ls="", ms=10)
    

    y= 阈值是您要观察交叉点的位置

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多