1

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?

1
  • Not sure what "pythonic" would refer to, but if you're looking for the most efficient or fastest method to draw many lines, this would be through a LineCollection. Commented Feb 20, 2019 at 1:47

2 Answers 2

4

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()
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.