Lyn*_*akr 6 r facet ggplot2 facet-grid
我想使用ggplot2's创建一个图形facet_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)
Run Code Online (Sandbox Code Playgroud)

这很好,但由于它出现在期刊文章中,因此每个面板也需要标有 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)
Run Code Online (Sandbox Code Playgroud)

由reprex 包(v0.2.1)于 2019 年 5 月 9 日创建
根据需要,我现在如何在每个面板上标记字母。但是,正如您所看到的,我的条形标签消失了!
我的问题:如何在保留条状标签的同时添加标签?
您可以在tag_facet 此处查看代码。如您所见,该函数明确且有意地删除了刻面条带(另请参阅文档中的“值” )。您可以通过创建自己的函数来解决这个问题,只需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)
}
Run Code Online (Sandbox Code Playgroud)
使用 {tagger} 包,这可以变得更简单一些。您可以tagger使用安装devtools::install_github("eliocamp/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()
Run Code Online (Sandbox Code Playgroud)
当然,我一问就立刻找到了解决办法。问题似乎是tag_facet将 strip labels 设置为element_blank,这可以通过调用后theme 调用来tag_facet修复。
# 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)
Run Code Online (Sandbox Code Playgroud)

由reprex 包(v0.2.1)于 2019-05-09 创建