Home > Back-end >  How to draw lines connecting only points with a distance equal to 1 in Python
How to draw lines connecting only points with a distance equal to 1 in Python

Time:06-14

For example, there is an array of coordinates of points:

coord = np.array([[0, 0], [0, 2], [0, 4], [1, 1], [1, 2], [1, 3], [1, 5], [2, 0], [2, 1], [2, 3], [2, 4], [3, 0], [3, 2], [3, 3], [3, 5], [4, 1], [4, 2], [4, 4]])

Plot:

plt.scatter(coord[:,0], coord[:,1])

enter image description here

And I want to draw lines between each pair of points with unit distance. Can you help me please to derive an algorithm to do that?

P.S. There is what I want to get:

(Yes, picture should include also diagonals of length sqrt(2).)

enter image description here

Thanks!

CodePudding user response:

You can use scipy.spatial.distance.pdist to compute the pairwise distances and filter. As the output of pdist is in a condensed form you need triu_indices to convert:

from scipy.spatial.distance import pdist

idx = np.vstack(np.triu_indices(len(coord), k=1)).T
d = pdist(coord)
coord[idx[d<=np.sqrt(2)]]

Output (pairs of points):

array([[[0, 0],
        [1, 1]],

       [[0, 2],
        [1, 1]],

       [[0, 2],
        [1, 2]],

       [[0, 2],
        [1, 3]],

       [[0, 4],
        [1, 3]],

       [[0, 4],
        [1, 5]],

       ...

       [[4, 1],
        [4, 2]]])
  • Related