如何合并facet_wrap2()中同标签的分面顶部标题框?
解决facet_wrap2合并相同分面标题的问题
要实现相同fourLoc标签的分面标题合并,只需在strip_themed()中启用合并功能,并调整strip背景色的设置逻辑,修改后的代码如下:
library(ggh4x) library(ggplot2) # 定义上下层strip的背景色 upper_fill <- c("#50808E", "#B4EDD2", "#E86A92", "#F6AE2D") lower_fill <- rep(c("#50808E", "#B4EDD2", "#E86A92"), 4) strip3 <- strip_themed( merge = TRUE, # 开启相同上层标签的合并 background_x = list( elem_rect(fill = upper_fill), # 上层fourLoc标签的背景色 elem_list_rect(fill = lower_fill) # 下层cond每个分面的背景色 ) ) p3 <- ggplot(wtf, aes(x=year, y=mAODscale, color=cond, group= interaction(year, spigroup))) + geom_point() + geom_hline(yintercept=0, color='grey') + stat_summary(aes(group=fourLoc), fun=median, geom='line', size=1) + facet_wrap2(~fourLoc + cond, strip=strip3, ncol=3) + labs(title = "Interaction between Dam and Month on Water Table Data", x = "Year (Mar-Feb)", y = "Scaled Water Table (mAOD)") + theme_bw() + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank()) plot(p3)
关键说明
merge = TRUE是核心设置,它会将fourLoc中相同的标签合并为一个跨列的标题框,不再重复显示。background_x改为列表结构,分别控制上层(fourLoc)和下层(cond)strip的背景色:- 上层用
elem_rect()设置每个fourLoc水平对应的背景色; - 下层用
elem_list_rect()保持你原有的每个分面单独上色的逻辑。
- 上层用
- 若
fourLoc不是因子类型,建议提前转换:wtf$fourLoc <- factor(wtf$fourLoc),确保合并逻辑准确执行。
内容的提问来源于stack exchange,提问作者Melanie Baker
相关产品推荐
相关产品推荐

