在ggplot2中一起使用构面标签和标签条

问题描述:

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

I'd like to create a figure using ggplot2's facet_grid, like below:

# 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,可以使用如下:

This is great, but since it's going in a journal article each panel also needs to be labelled with a, b, c, etc. The package egg has a great function for this called tag_facet, which is used as follows:

# 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软件包(v0.2.1)创建于2019-05-09 sup>

Created on 2019-05-09 by the reprex package (v0.2.1)

根据需要,我现在如何在每个面板上标记字母.但是,正如您所看到的,我的带标签已经消失了!

As required, I now how letter labels on each panel. But, as you can see, my strip labels have disappeared!

我的问题:如何保留带状标签,同时还要添加标签?

My question: How do I retain my strip labels, whilst also adding tags?

当然,我在询问后立即找到了解决方案.问题似乎是tag_facet将条形标签设置为element_blank,可以通过在调用tag_facet之后调用theme 来解决此问题.

Of course, I find a solution immediately after asking. The problem appears to be that tag_facet sets strip labels to element_blank, which can be fixed by calling theme after calling 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)

reprex软件包(v0.2.1)创建于2019-05-09 sup>

Created on 2019-05-09 by the reprex package (v0.2.1)