Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting lists of polygon coordinates in counter-clockwise direction in Python

Tags:

python

I have a number of sublists that contain coordinate tuples such that the tuples within a sublist form a polygon.

list_test = [[(0.115, 0.993), (0.319, 0.948), (0.236, 0.849)], [(0.319, 0.948), (0.640, 0.768), (0.236, 0.849), (0.471, 0.566)], [(0.115, -0.993), (-0.115, -0.993), (0.236, -0.849), (-0.236, -0.849), (0.0, -0.566)]]

These polygons are created by intersections of a rectangle and a line, so they can be a triangle, rectangle or pentagon (no "funny shapes" involved), and they all lie within the unit circle. How can I sort the coordinate tuples within each sublist in counter-clockwise direction?

like image 784
DominikR Avatar asked Mar 11 '26 12:03

DominikR


1 Answers

Just take the atan of each point based on origin and sort the values.

for points in list_test:
    points.sort(key=lambda x: math.atan2(x[1] - 0, x[0] - 0))

Simple plot for the given example:

fig, ax = plt.subplots()
for points in list_test:
    for point in points:
        ax.scatter(point[0], point[1], c='b')
        ax.annotate(f" {point}", xy=point)
ax.axhline(y=0, color='k')
ax.axvline(x=0, color='k')
plt.show()
like image 79
mustafasencer Avatar answered Mar 14 '26 01:03

mustafasencer