【问题标题】:Converting CSV file to shapefile - but want polygon not points将 CSV 文件转换为 shapefile - 但想要多边形而不是点
【发布时间】:2020-06-11 15:20:52
【问题描述】:

我有一个带有正方形坐标的 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)

我得到了这个情节

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

【问题讨论】:

    标签: r ggplot2 shapefile


    【解决方案1】:

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

    创建多边形后,您需要使用 st_sfc 将其转换为 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"))
    

    【讨论】:

    • 在我的数据框中,我实际上有 4 个正方形需要绘制。更改此代码以绘制 4 个多边形的最佳方法是什么?
    • @Alan20 如果您的数据框被称为df 并且您的列被称为shapelongitudelatitude,您可以使用lapply(split(df, df$shape), function(x) { coords &lt;- as.matrix(cbind(x$longitude, x$latitude)); rbind(coords, coords[1,])}) 创建一个适当矩阵的列表并传递这些到st_multipolygon
    • library(sfheaders) 可以从data.frames创建sf对象;特别是sfheaders::sf_polygon( obj = df, polygon_id = "shape")
    猜你喜欢
    • 2013-01-24
    • 2014-04-29
    • 1970-01-01
    • 2018-08-19
    • 1970-01-01
    • 1970-01-01
    • 2013-10-03
    • 2013-04-21
    • 1970-01-01
    相关资源
    最近更新 更多