Square
Square

Reputation: 149

Connecting two scattered point in lines using matplotlib

I am trying to connect two points using matplotlib. For example,

A=[[1,2],[3,4],[5,6]]
B=[8,1]

I should connect each (1,2), (3,4), (5,6) three points to (8,1), I tried to use method like (not this, but similar to this)

xs = [x[0] for x in A]
ys = [y[1] for y in A]
plt.plot(xs,ys)

but in that way, I should duplicate (8,1) every time between each three points.

Are there any pythonic method to do this?

Upvotes: 1

Views: 509

Answers (2)

Mr. T
Mr. T

Reputation: 12410

If you have more than one point B that you want to connect to each point A, you can use an itertools approach. Works of course also with only one point per list.

from matplotlib import pyplot as plt 
from itertools import product

A = [[1,2], [3,4], [5,6]]
B = [[8,1], [5,7], [3,1]]

for points in product(A, B):
    point1, point2 = zip(*points)
    plt.plot(point1, point2)

plt.show()

Upvotes: 4

jrd1
jrd1

Reputation: 10726

Actually, what you're trying to do is connect several points to one point, creating a line with each connection - a many-to-one mapping.

With that in mind, this is perfectly acceptable:

A=[[1,2],[3,4],[5,6]]
B=[8,1]

for point in A:
    connection_x = [point[0], B[0]]
    connection_y = [point[1], B[1]]
    plt.plot(connection_x, connection_y)
plt.show()

Which results in:enter image description here

Upvotes: 3

Related Questions