问题
I want to put black borders with labels and titles around each facet in facet_wrap
.
Something similar to this:
Sample data:
library(tidyverse)
mtcars %>%
mutate(gear = factor(gear, levels = c(4, 3, 5))) %>%
ggplot(aes(mpg, disp)) +
geom_point() +
geom_smooth(method = "lm") +
facet_wrap(~am + gear)
回答1:
You can do this by manually adding to the ggplot gtable
:
library(tidyverse)
library(grid)
library(gtable)
p <- mtcars %>%
mutate(gear = factor(gear, levels = c(4, 3, 5))) %>%
ggplot(aes(mpg, disp)) +
geom_point() +
geom_smooth(method = "lm") +
facet_wrap(~am + gear)
g <- ggplotGrob(p)
# add basic black rectangle round the columns
gt <- gtable_add_grob(g,
gList(
rectGrob(gp = gpar(col = "black", lwd=3, fill=NA)),
rectGrob(gp = gpar(col = "black", lwd=3, fill=NA))),
t=7, b=13, l=c(5, 9))
# look
# grid.newpage(); grid.draw(gt)
# add title above columns
tit1 <- textGrob("title1", x=0, hjust=0) ; tit2 = textGrob("title2", x=0, hjust=0)
gt <- gtable_add_rows(gt, grobHeight(tit1) + unit(0.5, "line"), 0)
gt <- gtable_add_grob(gt, gList(tit1, tit2), t=1, l=c(5, 9))
# draw
grid.newpage(); grid.draw(gt)
来源:https://stackoverflow.com/questions/59126171/create-border-and-title-for-each-column-in-facet-wrap