'R Buffer/Enlarge a polygon

I have a simple polygon.

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

Are there any R functions to increase the size of the polygon equally in all directions?

enter image description here

r


Solution 1:[1]

Using the sf package you can convert your polygon to a spatial object and use 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

Solution 2:[2]

For pure plotting purpose, I found this solution.

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

Note that ggforce 0.1.3 version on CRAN does not have this feature yet. The version on GitHub has this feature.

Solution 3:[3]

A lightweight implementation using the native plotting functions is available in the GrowPolygon() function, available in the the "Ternary" R package since version 2.1.0 (presently available via install.github("ms609/Ternary"), and coming soon to CRAN).

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)
polygon(Ternary::GrowPolygon(dfr, buffer = 0.2), border = 2)

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Spacedman
Solution 2 mindlessgreen
Solution 3 Martin Smith