在 ggplot2 中一起使用 facet 标签和 strip 标签

Using facet tags and strip labels together in ggplot2

我想使用 ggplot2facet_grid 创建一个图形,如下所示:

# Load ggplot2 library for plotting
library(ggplot2)

# Plot dummy data
p <- ggplot(mtcars, aes(mpg, wt)) 
p <- p + geom_point() 
p <- p + facet_grid(gear ~ cyl)
print(p)

这很好,但是因为它会出现在期刊文章中,每个面板还需要用 a、b、c 等标记。包 egg 有一个很棒的功能,叫做 tag_facet,用法如下:

# Load egg library for tagging
library(egg)
#> Warning: package 'egg' was built under R version 3.5.3
#> Loading required package: gridExtra

# Same plot but with tags for each facet
p <- ggplot(mtcars, aes(mpg, wt)) 
p <- p + geom_point() 
p <- p + facet_grid(gear ~ cyl)
tag_facet(p)

reprex package (v0.2.1)

于 2019-05-09 创建

根据需要,我现在如何在每个面板上标注字母。但是,如您所见,我的条带标签不见了!

我的问题:如何在添加标签的同时保留条带标签?

您可以查看 tag_facet here. As you can see, the function explicitly and deliberately removes the facet strips (see also the "value" in the documentation) 的代码。您可以通过创建自己的函数来解决这个问题,只需从原始代码中删除 theme 调用:

tag_facet2 <- function(p, open = "(", close = ")", tag_pool = letters, x = -Inf, y = Inf, 
    hjust = -0.5, vjust = 1.5, fontface = 2, family = "", ...) {

    gb <- ggplot_build(p)
    lay <- gb$layout$layout
    tags <- cbind(lay, label = paste0(open, tag_pool[lay$PANEL], close), x = x, y = y)
    p + geom_text(data = tags, aes_string(x = "x", y = "y", label = "label"), ..., hjust = hjust, 
        vjust = vjust, fontface = fontface, family = family, inherit.aes = FALSE)
}

当然是问了马上就找到解决办法了。问题似乎是 tag_facet 将条带标签设置为 element_blank,这可以通过在 调用 tag_facet 之后调用 theme 来解决。

# Load libraries
library(ggplot2)
library(egg)
#> Warning: package 'egg' was built under R version 3.5.3
#> Loading required package: gridExtra

# Create plot
p <- ggplot(mtcars, aes(mpg, wt)) 
p <- p + geom_point() 
p <- p + facet_grid(gear ~ cyl)
p <- tag_facet(p)
p <- p + theme(strip.text = element_text())
print(p)

reprex package (v0.2.1)

于 2019-05-09 创建

这只能使用 geom_text() 来完成:

data_text <- data.frame(
  cyl   = c(4, 6, 8, 4, 6, 8, 4, 6, 8),
  gear  = c(3, 3, 3, 4, 4, 4, 5, 5, 5)
  label = c('(a)', '(b)', '(c)', '(d)', '(e)', '(f)', '(g)', '(h)', '(i)')
)

ggplot(mtcars, aes(mpg, wt)) +
geom_point() +
facet_grid(gear ~ cyl) +
geom_text(data=data_text, aes(x=12, y=5, label=label), fontface='bold', size=4)

使用 {tagger} 包,这可以变得更简单一些。您可以使用 devtools::install_github("eliocamp/tagger") 安装 tagger。安装tagger后,让我们加载它。

library(tagger)
library(ggplot2)

# Plot dummy data
p <- ggplot(mtcars, aes(mpg, wt)) 
p <- p + geom_point() 
p + facet_grid(gear ~ cyl) + tag_facets()