2

I have this code to plot multiple lines(Fig1). How can I find the intersection points of these lines?

import matplotlib.pylab as pyl
import numpy as np
import math

x = [200, 300, 300, 200,200]
y = [150, 150, 100, 100,140]
x1 = [100, 400]
y1 = [50, 250]

pyl.plot(x, y, 'r')
pyl.plot(x1, y1, 'c')

pyl.xlim(0, 480)
pyl.ylim(0, 320)
pyl.grid(True)
pyl.show()

Fig1

smc
  • 205
  • 2
  • 10
  • 2
    Not with matplotlib: just calculate it (by hand) using the appropriate formula. – 9769953 Aug 30 '19 at 14:11
  • 1
    Possible duplicate of [How do I compute the intersection point of two lines?](https://stackoverflow.com/questions/20677795/how-do-i-compute-the-intersection-point-of-two-lines) ... or [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) – wwii Aug 30 '19 at 14:17

1 Answers1

2

I love Shapely for this kind of problems

from shapely.geometry import LineString, Polygon

x = [200, 300, 300, 200, 200]
y = [150, 150, 100, 100, 140]

x1, x2 = [100, 400]
y1, y2 = [50, 250]

poly = Polygon([(x, y) for x, y in zip(x, y)])
line = LineString([(x1, y1), (x2, y2)])

cross = poly.intersection(line)
[px1, px2], [py1, py2] = cross.coords.xy
p1 = (px1, py1) # (200, 116,66)
p2 = (px2, py2) # (250, 150)
BramAppel
  • 1,346
  • 1
  • 9
  • 21