Home > Mobile >  How to connect two line segments without changing their directions in matplotlib?
How to connect two line segments without changing their directions in matplotlib?

Time:01-26

Say I have two line segments with different slopes, one has x ranging from -0.5 to -0.1, the other has x ranging from 0 to 0.5. I want to use matplotlib to plot the two line segments into one line by connecting the two line segments. This is my current code

import numpy as np
from matplotlib import pyplot as plt

x = np.arange(-0.5, 0.51, 0.1)
y1 = np.linspace(2, 10.5, 5)
y2 = np.linspace(11, 1, 6)
plt.ylim([0, 14])
plt.plot(x, np.concatenate([y1,y2]), marker='o')
plt.show()

This will produce the following plot enter image description here

However, what I want is to extend the two line segments until their intersection. The expected plot looks something like below enter image description here

I want a general solution, which can generate such plot that connects any two given line segments y1 and y2. Note that I only want to have 11 markers. Any suggestions?

CodePudding user response:

You could do something like this (and format it better if you need) :

import numpy as np
from matplotlib import pyplot as plt
from scipy.stats import linregress

def line_intersect(m1, b1, m2, b2):
    x = (b2 - b1) / (m1 - m2)
    y = m1 * x   b1
    return x,y

x = np.arange(-0.5, 0.51, 0.1)
y1 = np.linspace(2, 10.5, 5)
y2 = np.linspace(11, 1, 6)

y1_lin = linregress(x[:2], y1[:2])
y2_lin = linregress(x[-2:], y2[-2:])

intersection_point = line_intersect(y1_lin.slope, y1_lin.intercept, y2_lin.slope, y2_lin.intercept)
x3 = np.array([x[0], intersection_point[0], x[-1]])
y3 = np.array([y1[0], intersection_point[1], y2[-1]])



plt.ylim([0, 14])
plt.plot(x, np.concatenate([y1,y2]), marker='o', color='blue', linestyle='None')
plt.plot(x3, y3, marker='', color='blue')
plt.show()

And that shows this: enter image description here

Basically, all that is happening is I calculate where the two lines intersect and use that to create a small new x, y mapping with 3 data points, the middle being the intersection point and the other ones the endpoints of the x.

  • Related