'R Buffer/Enlarge a polygon
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")
>
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()
# 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()
# 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()
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)
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 |