1

I have two curves where I would like to find their intersection point. The data could look something like this:

import matplotlib.pyplot as plt


y1 = [1, 5, 9, 14, 21, 27, 42, 50]
x1 = list(range(1, len(x1) + 1))

y2 = [60, 50, 40, 34, 30, 28, 23, 19, 16, 10, 5, 3]
x2 = list(range(5, len(x2) + 5))

plt.plot(x1, y1, marker="o")
plt.plot(x2, y2, marker="o")

plt.show()

Resulting in this:

enter image description here

As you can see they don't necessarily share the same x,y coordinates, i.e. it has to be the intersection between the lines that is drawn between the two pairs or dots/points.

Is there any way to achieve this ?

Denver Dang
  • 2,433
  • 3
  • 38
  • 68
  • Split your problem into two subproblems (1) First, identify the two pairs of points in question. (2) Find the intersections of the two lines defined by the two pairs of points. – Stef Jan 10 '22 at 14:22
  • See also https://stackoverflow.com/questions/28766692/intersection-of-two-graphs-in-python-find-the-x-value – Stef Jan 10 '22 at 14:24
  • Or you can do it manually. When you plot in pycharm(for instance), it opens a window, where you can see the coordinates of the cursor – bottledmind Jan 10 '22 at 14:25
  • This has nothing to do with Matplotlib. – 9769953 Jan 10 '22 at 14:29
  • @Stef [How to find the exact intersection of a curve (as np.array) with y==0?](https://stackoverflow.com/questions/46909373/how-to-find-the-exact-intersection-of-a-curve-as-np-array-with-y-0) finds the interpolated intersection points. [Intersection of two graphs in Python, find the x value](https://stackoverflow.com/questions/28766692/intersection-of-two-graphs-in-python-find-the-x-value) only finds the nearest value belonging to the curve. – JohanC Jan 10 '22 at 14:51
  • 1
    @stef At the end of the first answer of [How to find the exact intersection of a curve (as np.array) with y==0?](https://stackoverflow.com/questions/46909373/how-to-find-the-exact-intersection-of-a-curve-as-np-array-with-y-0) Ernest added an example how to use the same code to find the intersection between two curves (but that need to share their x-values; `np.interp()` can be used to put both curves on a common x-axis). – JohanC Jan 10 '22 at 17:09

1 Answers1

0

Since you can get the function of a line between two coordinates, you can can do the following:

  1. Identify in which box the intersection is e.g the two x and the two y-coordinates

  2. For each two consecutive point-pair (found in step 0) in the blue-graph i.e (X_blue[i],y_blue[i]) and (X_blue[i+1],y_blue[i+1]) get the analytical function of the line between the points. Do the same for the orange.

  3. For each blue-line check where it intersects with each orange-line. If it is within the box defined in (0) then you have it

Agreed, it's not going to be pretty but I don't see any other way (unless some library supports it)

CutePoison
  • 4,679
  • 5
  • 28
  • 63