【问题标题】:Is there a way to draw a polygon with specified point order ? (I now use the sf package in R)有没有办法用指定的点顺序绘制多边形? (我现在在 R 中使用 sf 包)
【发布时间】:2021-07-05 07:27:06
【问题描述】:

我在以下环境下运行以下代码:

R:4.1.0

包: 科幻:1.0.0 dplyr:1.0.7

看完之后 https://gis.stackexchange.com/questions/280671/r-create-multipolygon-from-overlapping-polygons-using-sf-package ,我在尝试玩 sf 包时遇到了一些问题。

我遇到的问题是以下代码:

library(sf)
library(dplyr)
poly <- data.frame(
  lon = c(0, 1, 1, 0, 0.5),
  lat = c(0, 0, 1, 1, 0.5),
  var = c(1, 1, 1, 1, 1)
) %>%
  st_as_sf(coords = c("lon", "lat"), dim = "XY") %>% st_set_crs(4326) %>% 
  group_by(var) %>%
  summarise() %>% st_cast("POLYGON")
plot(poly)

代码的输出图是the following

,我认为它会按照原始数据框的顺序来创建多边形。即 (0,0) -> (1,0) -> (1,1) -> (0,1) -> (0.5,0.5) -> (0,0),应该看起来像 this picture

我想知道是否有办法指定点连接的顺序?我在这个例子中使用了 set_convex_hull() 但输出只是一个正方形,这是有道理的,因为凸包的定义。我浏览了 sf 文档网站https://r-spatial.github.io/sf/articles/sf1.html,但仍然找不到解决方案。在研究这个包的使用时,我觉得我一定错过了一些关键词或方向。如果有人有任何建议,将不胜感激。

【问题讨论】:

    标签: r sf


    【解决方案1】:

    我一直发现从 data.frames 构建多边形很棘手,所以我编写了 sfheaders 库来简化此操作

    library(sf)
    library(sfheaders)
    
    poly <- data.frame(
      lon = c(0, 1, 1, 0, 0.5),
      lat = c(0, 0, 1, 1, 0.5),
      var = c(1, 1, 1, 1, 1)
    )
    
    sf <- sfheaders::sf_polygon(
      obj = poly
      , x = "lon"
      , y = "lat"
      , keep = T  ## To keep the 'var' variable
    ) 
    
    sf
    
    # Simple feature collection with 1 feature and 1 field
    # Geometry type: POLYGON
    # Dimension:     XY
    # Bounding box:  xmin: 0 ymin: 0 xmax: 1 ymax: 1
    # CRS:           NA
    #   var                       geometry
    # 1   1 POLYGON ((0 0, 1 0, 1 1, 0 ...
    

    这使用并维护输入数据帧中坐标的顺序。

    plot( sf )
    


    如果您想进行任何计算/几何运算,您需要在此对象上设置 CRS

    sf::st_crs(sf) <- 4326
    

    【讨论】:

    • 谢谢!这真的很有帮助。
    猜你喜欢
    • 2021-07-14
    • 2021-08-15
    • 2018-07-24
    • 2014-08-08
    • 1970-01-01
    • 1970-01-01
    • 2019-03-02
    • 2022-11-10
    • 1970-01-01
    相关资源
    最近更新 更多