Reputation: 229
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()
Upvotes: 1
Views: 1054
Reputation: 12496
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
Upvotes: 1
Reputation: 475
This code prints 'intersect' if the y-values cross each other at some point.
mark = y1[0]-y2[0]
for i in range(len(y1)):
if mark > 0:
if y1[i]-y2[i] < 0:
print('intersect')
elif mark < 0:
if y1[i]-y2[i] > 0:
print('intersect')
Upvotes: 0