如何相对于中心按顺时针顺序对 R 中的点进行排序?

How do I sort points in clockwise order in R with respect to the center?

我有一个包含 X 和 Y 坐标的数据集,我正在尝试找出一种方法,将它们从 R 中的中心顺时针(或逆时针)方向排序。假设以经纬度的中位数为中心。

样本数据:

df <- structure(list(name = c("A", "B", "C", "D", "E", "F", "G", "H", 
                              "I", "J"), lat = c(22.57, 22.69, 22.72, 22.5, 22.66, 22.19, 22.6, 
                                                 22.27, 22.31, 22.15), lon = c(88.69, 88.84, 88.77, 88.85, 88.63, 
                                                                               88.91, 88.54, 88.62, 88.78, 88.66)), class = "data.frame", row.names = c(NA, 
                                                                                                                                                        -10L))

我要找的是说,上图中的点可以这样排序:G -> E -> A-> C -> B 等等。

到目前为止,我尝试过用arc tan函数计算极坐标,然后对它们进行排序,但结果并不理想。

我也试过orderPoints函数,但是那里的排序也有疑问。我得到的顺序是这样的:D-> F-> G-> B-> H-> J-> I-> E-> C-> A。虽然其中一些看起来是有序的,但其他的是远眺

(正如@thelatemail 指出的那样,答案将取决于假设哪个点是点排列的中心。下面的方法采用靠近中点的点,选择它来提供您期望的顺序。实际中位点会在E之前显示A。)

df$angle = atan2(df$lat - 22.5,
                 df$lon - 88.68)
library(ggplot2)
ggplot(df[order(df$angle, decreasing = TRUE), ], 
       aes(lon, lat, color = angle, label = name)) +
  geom_path(arrow = arrow(type = "closed", length = unit(0.05, "npc"))) + 
  geom_text(size = 8, color = "black") +
  annotate("point", x = 88.68, y = 22.5, color = "red")