Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
775 views
in Technique[技术] by (71.8m points)

r - Using facet tags and strip labels together in ggplot2

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)

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)

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can view the code for tag_facet here. As you can see, the function explicitly and deliberately removes the facet strips (see also the "value" in the documentation). You can fix that by creating your own function, and just removing the theme call from the original code:

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)
}

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...