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?

Suh Fangmbeng
  • 573
  • 4
  • 16
Square
  • 149
  • 1
  • 8
  • 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`](https://stackoverflow.com/questions/54492963/many-plots-in-less-time-python/54544965#54544965). – ImportanceOfBeingErnest Feb 20 '19 at 01:47

2 Answers2

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()
Mr. T
  • 11,960
  • 10
  • 32
  • 54
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

jrd1
  • 10,358
  • 4
  • 34
  • 51