I have a set of points which outline a map region. I want to use these points to define a polygon that I can plot with ggplot using the simple features (sf) library. However, the points are out of order, so a line connecting them does't form a closed shape. I have tried both geom_line and geom_path. Is there any way I might be able to get these re-organized without having to manually order them?
In the reproducible example below, "good circle" is what I want, while "bad circle" is what I have. They include all of the same x,y points, but due to bad circle being out of order I can't make a closed figure.
library(dplyr)
library(ggplot2)
library(sf)
x_coords <- rad * cos(seq(0, (2 * pi), (pi / 6)))
y_coords <- rad * sin(seq(0, (2 * pi), (pi / 6)))
perimeter <- as.matrix(rbind(cbind(x_coords, y_coords), c(x_coords[1], y_coords[1])))
perimeter
good_circle = st_multipolygon(list(list(perimeter)))
ggplot() geom_sf(data = good_circle, fill = "blue") ggtitle("good circle")
What I have looks like this:
bad_circle <- slice(data.frame(perimeter), sample(1:n()))
ggplot(bad_circle, aes(x = x_coords, y = y_coords)) geom_point() geom_line() ggtitle("bad circle")
CodePudding user response:
I propose you a different approach. Instead of reordering points, you can create a