简体   繁体   中英

how can I find intersection of multiple lines with a curve?

I have a file which has x and y. For each line that passes from the y-axis, I can find the intersection but I wanted to have an automatic way to find the intersections of a bunch lines that pass from y-axis like the figure below:

perspective result在此处输入图像描述

the code that I have written for finding intersections one-by-one is below:

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)

the thing that I have

Current result在此处输入图像描述

You can try to set up an extra loop to check for multiple intersection values which you input and use dictionary to hold list of matches against intersection value as key. This theoretically should plot all intersections of y you desire into same graph

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)

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)

the y= treshold is where you want to watch the intersection

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM