I want to add a facet title as strip over a facetted plot in ggplot2
. My MWE throws an error. Any help will be highly appreciated. Thanks
library(ggplot2)
library(gtable)
p <- ggplot(mtcars, aes(mpg, wt)) + geom_point()
p <- p + facet_grid(. ~ cyl)
# get gtable object
Plot1 <- ggplot_gtable(ggplot_build(p))
# add label for top strip
Plot1 <- gtable_add_rows(Plot1, Plot1$heights[[3]], 2)
Plot1 <- gtable_add_grob(Plot1,
list(rectGrob(gp = gpar(col = NA, fill = gray(0.5))),
textGrob("Cyl", gp = gpar(col = gray(1)))),
3, 4, 3, 10, name = paste(runif(2)))
# add margins
Plot1 <- gtable_add_rows(Plot1, unit(1/8, "line"), 2)
# draw it
grid.newpage()
print(grid.draw(Plot1))
Edit Updating to ggplot version 3.0.0
I think you were close. You had the row and column numbers wrong in the add grob command. Your new strip spans columns 5 to 9; that is, change 10 to 9 in the add grob command.
OR, to add a new strip to the right: