首页 > 解决方案 > 将 CSV 文件转换为 shapefile - 但想要多边形而不是点

问题描述

我有一个带有正方形坐标的 csv 数据框。我已将 csv 转换为 shapefile,但它绘制为四个单独的点,我希望该图显示一个正方形。

  Shape long lat
1   1.1   43  10
2   1.1   43  13
3   1.1   40  13
4   1.1   40  10

我已将其转换为 shapefile 并为其提供坐标参考系统,如下所示:

test <- as.data.frame(read_csv("/Users/alan/Desktop/Test.csv"))
Coord_Ref <- st_crs(3035)
plot_locations_test <- st_as_sf(test, coords = c("long", "lat"), crs =Coord_Ref)

然后我可以使用 ggplot 绘制 shapefile

ggplot() +geom_sf(data = plot_locations_test)

我得到了这个情节 在此处输入图像描述

我怎样才能使它成为一个填充的正方形而不是单独的点?

标签: rggplot2shapefile

解决方案


您需要从数据点创建一个简单的多边形,确保形状是闭合的(即第一个点必须与最后一个点相同)。您将经度/纬度列转换为矩阵并将其放入列表中以传递给st_polygon.

创建多边形后,您需要使用以下命令将其转换为 sfc st_sfc

test <- as.matrix(rbind(test[,-1], test[1, -1]))

Coord_Ref <- st_crs(3035)
plot_locations_test <- st_polygon(x = list(test))
plot_locations_test <- st_sfc(plot_locations_test, crs = Coord_Ref)
ggplot(plot_locations_test) + geom_sf(fill = "red", alpha = 0.1)

在此处输入图像描述

数据

test <- structure(list(Shape = c(1.1, 1.1, 1.1, 1.1), 
                       long = c(43L, 43L, 40L, 40L), 
                       lat = c(10L, 13L, 13L, 10L)), 
                  class = "data.frame", 
                  row.names = c("1", "2", "3", "4"))

推荐阅读