Home > Back-end >  How to sort a list of points in clockwise/anti-clockwise in Python?
How to sort a list of points in clockwise/anti-clockwise in Python?

Time:09-17

I got a list of coordinate points, and I would like to sort them in either clockwise/anti-clockwise.

This is the list I mentioned:
[(985, 268), (112, 316), (998, 448), (1018, 453), (1279, 577), (1196, 477), (1161, 443), (986, 0), (830, 0), (983, 230), (998, 425), (998, 255)]

These coordinate points will help me to draw the line segments of an object. Below is an image for illustration. As you can see, I have marked down all the points in the list in this image.

And my goal is to sort these coordinate points in order to create several line segments. Therefore, my expected result would be as follow:
Anti-Clockwise Direction: [(985, 268), (998, 425), (112, 316), (998, 448), (1018, 453), (1279, 577), (1196, 477), (1161, 443), (998, 255), (986, 0), (983, 230), (830, 0)]

Clockwise Direction: [(985, 268), (830, 0),(983, 230), (986, 0), (998, 255), (1161, 443), (1196, 477), (1279, 577), (1018, 453), (998, 448), (112, 316), (998, 425)]

So far, I have taken a website, Counterclockwise around barycentre

points = sort_counterclockwise(points, (0,0))
plt.plot([x for x,_ in points], [y for _,y in points])
plt.show()

Counterclockwise around (0, 0)

points = sort_counterclockwise(points, (1000, 200))
plt.plot([x for x,_ in points], [y for _,y in points])
plt.show()

Counterclockwise around (1000, 200)

  • Related