title: Python: point on a line closest to third point
body: <p>I have a line/vector between two XY points (p1 and p2) and a third XY point (p3) that is outside the line. According to <a href="https://stackoverflow.com/questions/40970478/python-3-5-2-distance-from-a-point-to-a-line">this post</a> I know how to get the distance of that point to the line. But what I'm actually looking for is a point (p4) on that line that is in a minimum distance (d) to the third point (p3). I found <a href="https://stackoverflow.com/questions/32281168/find-a-point-on-a-line-closest-to-a-third-point-javascript">this post</a>, but I feel it's not the correct solution. Maybe there's something included in Numpy or Python?</p>
  
  <p><a href="https://i.stack.imgur.com/v0O6S.png" rel="noreferrer"><img src="https://i.stack.imgur.com/v0O6S.png" alt="distance of a point to a line including crossing point"></a></p>
  
  <p>According to @allo I tried the following. You can download my code as <a href="http://www.matthias-heise.eu/stackoverflow/point_to_line.py" rel="noreferrer">Python file</a> or <a href="http://www.matthias-heise.eu/stackoverflow/point_to_line.ipynb" rel="noreferrer">Jupyter Notebook</a> (both Python3).</p>
  
  <pre><code>points = [[1, 1], [3, 1], [2.5, 2], [2.5, 1]]
  import matplotlib.pyplot as plt
  %matplotlib inline
  
  fig, ax = plt.subplots()
  fig.set_size_inches(6,6)
  
  x, y = zip(*points[:2])
  l1, = ax.plot(x,y, color='blue')
  scatter1 = ax.scatter(x=x,y=y, color='blue', marker='x', s=80, alpha=1.0)
  
  x, y = zip(*points[2:])
  l2, = ax.plot(x,y, color='red')
  scatter2 = ax.scatter(x=x,y=y, color='red', marker='x', s=80, alpha=1.0)
  
  p1 = Vector2D(*points[0])
  p2 = Vector2D(*points[1])
  p3 = Vector2D(*points[2])
  
  p1p2 = p2.sub_vector(p1)
  p1p3 = p3.sub_vector(p1)
  
  angle_p1p2_p1p3 = p1p2.get_angle_radians(p1p3)
  length_p1p3 = p1p3.get_length()
  length_p1p2 = p1p2.get_length()
  
  p4 = p1.add_vector(p1p2.multiply(p1p3.get_length()/p1p2.get_length()).multiply(math.cos(p1p2.get_angle_radians(p1p3))))
  
  #p4 = p1 + p1p2 * length(p1p3)/length(p1p2)*cos(angle(p1p2, p1p3))
  
  p4 = p1.add_vector(p1p2.multiply(length_p1p3/length_p1p2*math.cos(angle_p1p2_p1p3)))
  p4
  </code></pre>
  
  <p>Which results in p4 = <strong>(1.8062257748298551, 1.0)</strong> but should obviously be <strong>(2.5, 1.0)</strong>.</p>
  
  <p><a href="https://i.stack.imgur.com/3vYUx.png" rel="noreferrer"><img src="https://i.stack.imgur.com/3vYUx.png" alt="point p4 to line p1p2"></a></p>