如何使用ggarrange将编号/字母标签置于子图下方?
问题:将ggarrange子图标签移至x轴标签下方
我正尝试使用ggarrange制作多图,希望将编号/字母标签放在每个子图的x轴标签下方。以下示例代码生成的标签内容正确,但位置错误,出现在子图标题旁而非目标位置,求解决方法。
library(ggplot2) library(ggpubr) gg1 <- ggplot(mtcars,aes(x=hp,y=mpg))+ geom_point(aes(color=factor(cyl)),alpha=.5)+ stat_smooth(method='lm', se=F, color='red')+ ggtitle('plot 1')+ theme_bw()+ theme(aspect.ratio=1, legend.position = c(1, 1), legend.justification = c(1,1), legend.background = element_rect(colour = NA, fill = NA)) gg2 <- ggplot(mtcars)+ geom_density(aes(x=hp, color=factor(cyl)))+ ggtitle('plot 2')+ theme_bw()+ theme(aspect.ratio=1, legend.position = c(1, 1), legend.justification = c(1,1), legend.background = element_rect(colour = NA, fill = NA)) gg3 <- ggplot(mtcars)+ geom_density(aes(x=mpg, color=factor(cyl)))+ ggtitle('plot 3')+ theme_bw()+ theme(aspect.ratio=1, legend.position = c(1, 1), legend.justification = c(1,1), legend.background = element_rect(colour = NA, fill = NA)) gg4 <- ggplot(mtcars,aes(x=hp,y=mpg))+ geom_point(aes(color=factor(cyl)),alpha=.5)+ stat_smooth(method='lm', se=F, color='red')+ ggtitle('plot 4')+ theme_bw()+ theme(aspect.ratio=1, legend.position = c(1, 1), legend.justification = c(1,1), legend.background = element_rect(colour = NA, fill = NA)) ggarrange(gg1,gg2,gg3,gg4, nrow = 2, ncol = 2, labels = paste0("(",letters[1:4],")"))
生成的标签默认位于子图左上角(标题旁),而非目标的x轴标签下方。
解决方案
方法1:调整ggarrange自带标签的位置
直接通过ggarrange()的参数控制标签位置,无需修改子图本身:
ggarrange(gg1, gg2, gg3, gg4, nrow = 2, ncol = 2, labels = paste0("(", letters[1:4], ")"), label.x = 0.5, # 水平居中对齐x轴 label.y = -0.1, # 将标签移到子图底部外侧,数值可根据布局微调 label.position = "bottom", font.label = list(size = 10, face = "bold"))
label.x = 0.5确保标签在水平方向居中label.y = -0.1让标签处于子图主体下方(负数表示超出子图范围),如果位置不合适,可以改成-0.08或-0.12这类数值font.label可以自定义标签的字体大小和样式
方法2:给每个子图添加底部注释(更灵活)
如果需要更精细的位置控制(比如左对齐、右对齐),可以给每个ggplot对象单独添加标签:
# 定义批量添加标签的函数 add_subplot_label <- function(plot, label) { plot + annotate("text", x = Inf, y = -Inf, label = label, hjust = 1, vjust = 1, # 右下角对齐,可改成hjust=0左对齐 size = 4, face = "bold", margin = margin(t = 10)) # 控制与x轴的间距 } # 给每个子图加上标签 gg1_labeled <- add_subplot_label(gg1, "(a)") gg2_labeled <- add_subplot_label(gg2, "(b)") gg3_labeled <- add_subplot_label(gg3, "(c)") gg4_labeled <- add_subplot_label(gg4, "(d)") # 重新排列子图 ggarrange(gg1_labeled, gg2_labeled, gg3_labeled, gg4_labeled, nrow = 2, ncol = 2)
这种方式可以自由调整标签的对齐方式和位置,修改x、y、hjust参数就能实现不同的布局效果。
内容的提问来源于stack exchange,提问作者FredrikH-R
相关产品推荐
相关产品推荐

