Home > Net >  How to detect if there is intersection using matplotlib?
How to detect if there is intersection using matplotlib?

Time:09-21

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()

enter image description here

CodePudding user response:

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
    

    enter image description here

  • 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
    

    enter image description here

CodePudding user response:

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')
  • Related