ggplot2分面图轴标签调整:移除首分面标签并居中
实现背靠背金字塔图的分面标签居中调整
以下是修改后的代码,可实现你想要的效果:
library(ggplot2) library(ggh4x) data <- data.frame(group = c("Group 1", "Group 1", "Group 2", "Group 2", "Group 1", "Group 1", "Group 2", "Group 2", "Group 1", "Group 1", "Group 2", "Group 2"), administered = c("no", "yes", "no", "yes", "no", "yes", "no", "yes", "no", "yes", "no", "yes"), medication = c("DRUG A with a long name", "DRUG A with a long name", "DRUG A with a long name", "DRUG A with a long name", "DRUG B", "DRUG B", "DRUG B", "DRUG B", "DRUG C", "DRUG C", "DRUG C", "DRUG C"), count = c(100,200,50,88,99,300,77,45,12,0,9,27)) ggplot(data, aes(x = medication, y = count, fill = administered)) + geom_col(position = "fill") + ylab("proportion") + scale_fill_manual(values = c("no"="#FF0000FF", "yes"="#0000FFFF"))+ theme(axis.ticks.y = element_blank(), # 隐藏原有分面标签及背景 strip.text = element_blank(), strip.background = element_blank()) + facet_wrap2(~ group, scales = "free") + facetted_pos_scales(y = list( scale_y_reverse(labels = scales::percent), scale_y_continuous(labels = scales::percent))) + coord_flip() + # 给指定分面添加顶部居中标签 annotate_outside("text", label = "Group 1", x = 0.5, y = Inf, vjust = 1.2, facet = ~ group == "Group 1") + annotate_outside("text", label = "Group 2", x = 0.5, y = Inf, vjust = 1.2, facet = ~ group == "Group 2")
关键修改说明:
- 移除默认分面标签:通过
theme设置strip.text = element_blank()隐藏原有标签,strip.background = element_blank()去掉分面标签的背景框 - 添加自定义居中标签:利用
ggh4x的annotate_outside函数,精准指定标签所属的分面(通过facet参数),x=0.5保证标签在分面水平居中,y=Inf定位到分面顶部,vjust=1.2微调文本位置,避免与绘图区域重叠
内容的提问来源于stack exchange,提问作者Klaus Peter
相关产品推荐
相关产品推荐

