I want to connect a set of points to create a polygon. I tried connecting points clockwise, but did not receive the expected results. Could anyone suggest how to improve the code so that I could get the proper result or what other methods I would use to connect the point
My points coordinates:
[<POINT (435099.004 121451.158)>,
<POINT (435109.204 121451.579)>,
<POINT (435099.604 121441.77)>,
<POINT (435128.704 121459.57)>,
<POINT (435120.604 121452.07)>,
<POINT (435121.204 121442.37)>,
<POINT (435128.904 121450.87)>,
<POINT (435109.104 121441.67)>,
<POINT (435120.954 121450.67)>,
<POINT (435111.204 121451.668)>,
<POINT (435120.204 121459.27)>,
<POINT (435109.204 121449.27)>,
<POINT (435111.204 121449.27)>]
Approach connecting points clockwise:
def calculate_angle(p1, p2):
return math.atan2(p2.y - p1.y, p2.x - p1.x)
def find_lowest_point(points):
lowest_point = min(points, key=lambda p: (p.x, p.y))
return lowest_point
enter def connect_points_clockwise(points):
lowest_point = find_lowest_point(points)
sorted_points = sorted(points, key=lambda p: calculate_angle(lowest_point, p))
connected_points = []
for i in range(len(sorted_points)):
start_point = sorted_points[i]
end_point = sorted_points[(i + 1) % len(sorted_points)]
connected_points.append((start_point, end_point))
def connect_points_clockwise(points):
lowest_point = find_lowest_point(points)
sorted_points = sorted(points, key=lambda p: calculate_angle(lowest_point, p))
connected_points = []
for i in range(len(sorted_points)):
start_point = sorted_points[i]
end_point = sorted_points[(i + 1) % len(sorted_points)]
connected_points.append((start_point, end_point))
return connected_points
def display_polygon(points):
plt.figure()
ax = plt.gca()
# Extract x and y coordinates from points
x_coords = [p.x for p in points]
y_coords = [p.y for p in points]
# Create a Polygon patch
#polygon = Polygon([(p.x, p.y) for p in points], fill=None)
#ax.add_patch(polygon)
# Plot points with numbers
for i, p in enumerate(points):
plt.text(p.x, p.y, str(i + 1), fontsize=12, ha='center', va='center', color='red')
# Plot points
plt.plot(x_coords, y_coords, 'bo')
plt.xlabel('X')
plt.ylabel('Y')
plt.title('Polygon from Points')
plt.axis('equal')
plt.show()
# Connect points clockwise
connected_points = connect_points_clockwise(new_points)
Results is presented in Figure Polygon_from_points
And the polygon I would like to generate should align with what is presented in Figure outline_34