为使用facet_wrap (ggplot2) 创建的每个子图添加标签

Jos*_*lhj 5 r ggplot2 facet-wrap

我对 ggplot2(和 R)还很陌生,所以请耐心等待。使用facet_wrap,我创建了一个多面板图。我想用字母来标记它们(从左上角的面板(A)开始,下一个面板(b)等),但我不知道如何去做。我希望它位于绘图之外(最好位于每个面板的左上角)。

我遇到了grid.textggtitle,但我不确定如何实施这些才能获得预期的结果。

我看到这篇文章,根据给出的答案,似乎可以手动标记每个图,但我希望标记能够按顺序自动完成。

我将非常感谢任何建议/指南。

bap*_*ste 6

p <- qplot(displ, hwy, data = mpg) + facet_wrap(~ cyl) + 
    theme(panel.margin=unit(1,"line"))

library(gtable)
g <- ggplotGrob(p)
strips <- g$layout[grep("strip_t", g$layout$name), ]
titles <- lapply(paste0("(", letters[seq_len(nrow(strips))], ")"), 
                 textGrob, x = 0, hjust = 0, vjust = 1)
g <- gtable_add_grob(g, grobs = titles, 
                     t = strips$t, b = strips$b - 2, 
                     l = strips$l, r = strips$r)
grid.newpage()
grid.draw(g)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述