SAMCRO
SAMCRO

Reputation: 137

python drawing a line outlining two lines

I would like to know how to smoothly draw a line on top of two lines I have. Take for example the following code:

import matplotlib.pyplot as plt
x1, y1 = [-1, 12], [1, 4]
x2, y2 = [1, 10], [3, 2]
plt.plot(x1, y1, x2, y2, marker = 'o')
plt.show()

I would like a draw a line from the top orange dot down to the blue line where they intersect and up to the top right blue dot. I want this line to be smooth preferably. How do I do this?

I was thinking I could make an array of the orange line to the blue then have an array of the blue line till the blue dot. I would then draw a line here but this is quite a crude solution. I am not sure if there is something smarter I can do.

Also it would be good to know how to generalise this to smooth lines (which is why I don't want this array solution). Thanks in advance.

Upvotes: 0

Views: 357

Answers (1)

xszym
xszym

Reputation: 938

first you have to calculate intersection between lines. I gave you example how to do it. Function draw_smooth_line will draw smooth line between 3 points. You can add logic to getting top points from you list if you need it.

import matplotlib.pyplot as plt
from scipy.ndimage.filters import gaussian_filter1d
import numpy as np 
from scipy.interpolate import interp1d



def draw_smooth_line(left_x, left_y, mid_x, mid_y, right_x, right_y):
    x = [left_x, mid_x, right_x]
    y = [left_y, mid_y, right_y]
    x_new = np.linspace(left_x, right_x,500)
    f = interp1d(x, y, kind='quadratic')
    y_smooth=f(x_new)
    plt.plot (x_new,y_smooth)


def findIntersection(x1,y1,x2,y2,x3,y3,x4,y4):
    px= ( (x1*y2-y1*x2)*(x3-x4)-(x1-x2)*(x3*y4-y3*x4) ) / ( (x1-x2)*(y3-y4)-(y1-y2)*(x3-x4) ) 
    py= ( (x1*y2-y1*x2)*(y3-y4)-(y1-y2)*(x3*y4-y3*x4) ) / ( (x1-x2)*(y3-y4)-(y1-y2)*(x3-x4) )
    return [px, py]

x1, y1 = [-1, 12], [1, 4]
x2, y2 = [1, 10], [3, 2]

x3, y3 = findIntersection(x1[0],y1[0],x1[1],y1[1],x2[0],y2[0],x2[1],y2[1])

draw_smooth_line(x1[1], y1[1], x3, y3, x2[0], y2[0])

plt.plot(x1, y1, x2, y2, x3, y3, marker = 'o')

plt.show()

Here is result

result

Upvotes: 1

Related Questions