I want to create a hexagon that surrounds the plot created from the following code:
data.frame(x=rep(2000:2001,each=3),
y=rep(c("Jan","Feb","Mar"),2)) %>%
ggplot()
geom_point(aes(factor(x),y),shape=21,size=25)
coord_fixed()
I want the output something like this:

I first looked into how we could change the panel shape itself but couldn't find any solutions. Then I looked into creating a hexagon using ggforce package but with no luck either. I tried:
ggforce::geom_regon(aes(x0= ? ,y0= ?,sides=6,angle=0,r= ?))
but couldn't find apropriate values for the x0,y0 and r arguments.
CodePudding user response:
One option would be to add a polygon via annotation_custom which requires to set clip="off" and to increase the plot margins. A drawback is that the last step involves some fiddling to get the right values for the margins:
library(ggplot2)
library(grid)
df <- data.frame(
x = rep(2000:2001, each = 3),
y = rep(c("Jan", "Feb", "Mar"), 2)
)
base <- ggplot(df)
geom_point(aes(factor(x), y), shape = 21, size = 25)
coord_fixed(clip = "off")
grob <- grid::polygonGrob(
x = c(0, 0.5, 1, 1, 0.5, 0), y = c(0, -.25, 0, 1, 1.25, 1),
gp = grid::gpar(fill = NA, lwd = unit(2, "lines"))
)
base
annotation_custom(grob = grob)
theme(plot.margin = margin(t = 66, r = 5.5, b = 66, l = 5.5, "pt"))

