Ethan Gonzaga
Ethan Gonzaga

Reputation: 21

How can I draw a line from one point to a list multiple points

I'm quite new(ish) to python, so sorry if my syntax is basic or just downright bad.

I'm trying to create a simple 2D Line of Sight script where one point draws a line to all the other points using Matplotlib.

list of points in Matplotlib

Currently, I have a list of points, but I'm having trouble writing the For loop for it. My idea was to create a For loop to draw the lines from the origin to all the x,y coords as defined in positions, but it unfortunately doesn't work.

quality = 5
x = np.linspace(-1,1,quality)
y = np.linspace(-1,1,quality)
X,Y = np.meshgrid(x,y)

positions = np.vstack([Y.ravel(), X.ravel()])

plt.scatter(*positions[::-1])
plt.show()

origin = [0,0]

for i in range(len(positions)):
    for j in range(len(positions[i])):
        x1 = positions[0][j]
        y1 = positions[1][j]
        line = shapely.geometry.LineString([origin, [x1, y1]])
        

But when i run this script, all i get is this output.

What I'm trying to accomplish is something similar to the image below that I've done in another software.

points connect to all points

Upvotes: 0

Views: 1675

Answers (1)

r-beginners
r-beginners

Reputation: 35275

'shapely' is something I've never used before, but I've tried to recreate it by introducing a live riley, and I had to assign the coordinate information on shapely to a variable in matplotlib. The answer I was referring to is this.

import numpy as np
import matplotlib.pyplot as plt
from shapely.geometry import LineString

quality = 5
x = np.linspace(-1,1,quality)
y = np.linspace(-1,1,quality)
X,Y = np.meshgrid(x,y)

positions = np.vstack([Y.ravel(), X.ravel()])

plt.scatter(*positions[::-1])

origin = (0, 0)

for i in range(len(positions)):
    for j in range(len(positions[i])):
        x1 = positions[0][j]
        y1 = positions[1][j]
        line = LineString([origin, (x1, y1)])
        x2, y2 = line.xy
        plt.plot(0, 0, x2, y2)

plt.show()

enter image description here

Upvotes: 1

Related Questions