Issue
I am using matplotlib to plot these two line graphs. However, only sometimes my graphs would have an intersection. How can I detect if my line graphs have an intersection?
df = pd.read_csv("test.csv")
df2 = pd.read_csv("test2.csv")
x1 = df['A'].tolist()
x1 = np.array(x1)
y1 = df['D'].tolist()
y1 = np.array(y1)
x2 = df2['X'].tolist()
x2 = np.array(x2)
y2 = df2['Y'].tolist()
y2 = np.array(y2)
plt.plot(x1,y1)
plt.plot(x2,y2)
plt.show()
Solution
You can compute the index of intersection points with:
idx = np.argwhere(np.diff(np.sign(y1 - y2))).flatten()
If there is one or more intersections, idx
is a list of intersection points indeces, otherwise it is an empty list.
one or more intersections
import numpy as np import matplotlib.pyplot as plt x1 = np.linspace(0, 10, 1000) x2 = np.linspace(-2, 5, 1000) y1 = np.sin(x1) y2 = np.cos(x2) + 1 idx = np.argwhere(np.diff(np.sign(y1 - y2))).flatten() fig, ax = plt.subplots() ax.plot(x1, y1, 'blue') ax.plot(x2, y2, 'red') plt.show()
print(len(idx)) 2
no intersections
import numpy as np import matplotlib.pyplot as plt x1 = np.linspace(0, 10, 1000) x2 = np.linspace(-2, 5, 1000) y1 = np.sin(x1) y2 = np.cos(x2) + 2 idx = np.argwhere(np.diff(np.sign(y1 - y2))).flatten() fig, ax = plt.subplots() ax.plot(x1, y1, 'blue') ax.plot(x2, y2, 'red') plt.show()
print(len(idx)) 0
Answered By - Zephyr
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.