代码之家  ›  专栏  ›  技术社区  ›  mindlessgreen

R缓冲/放大多边形

r
  •  1
  • mindlessgreen  · 技术社区  · 6 年前

    我有一个简单的多边形。

    dfr <- data.frame(x=c(2,2.5,4,5,4.5,3,2),y=c(2,3,3.5,3,2.8,2.5,2))
    plot(dfr)
    polygon(dfr)
    

    enter image description here

    有没有R函数可以在所有方向上均匀地增加多边形的大小?

    enter image description here

    2 回复  |  直到 6 年前
        1
  •  4
  •   Spacedman    6 年前

    使用 sf 包可以将多边形转换为空间对象并使用 st_buffer :

    > p = st_polygon(list(as.matrix(dfr)))
    > pbuf = st_buffer(p, .4)
    > plot(pbuf)
    > plot(p,add=TRUE,col="red")
    > 
    

    enter image description here

        2
  •  0
  •   mindlessgreen    6 年前

    纯粹出于策划的目的,我找到了这个解决方案。

    library(ggplot2)
    dfr <- data.frame(x=c(2,2.5,4,5,4.5,3,2),y=c(2,3,3.5,3,2.8,2.5,2))
    
    # vanilla polygon
    ggplot(dfr,aes(x,y))+
      geom_polygon(fill=NA,col="black")+
      theme_minimal()
    

    enter image description here

    # enlarge polygon
    library(ggforce)
    ggplot(dfr,aes(x,y))+
      geom_polygon(fill=NA,col="black")+
      geom_shape(fill=NA,col="red",expand=unit(0.2,"cm"))+
      theme_minimal()
    

    enter image description here

    # enlarge with pretty curved edges
    library(ggforce)
    ggplot(dfr,aes(x,y))+
      geom_polygon(fill=NA,col="black")+
      geom_shape(fill=NA,col="red",expand=unit(0.2,"cm"),radius=unit(0.2,"cm"))+
      theme_minimal()
    

    enter image description here

    请注意 ggforce 0.1.3 CRAN上的版本还没有此功能。上的版本 GitHub 具有此功能。