ggarrange中不同长度图例标题的左对齐问题求助
解决多组绘图共享图例时的左对齐问题
要解决不同长度图例标题导致的图例无法左对齐的问题,你可以通过统一图例宽度和设置图例标题左对齐来实现,具体步骤如下:
修改图例设置
调整图例的标题对齐方式为左对齐,同时为两个图例设置相同的固定宽度,确保它们的水平占位一致:
##### Loading libraries library(ggplot2) library(ggpubr) library(gridExtra) library(lemon) library(grid) ##### Initiating objects ### Colors dfCol1 <- data.frame(Groups=0:3, col=c("grey80", "#87c5ff", "#477cad", "#113c63")) dfCol2 <- data.frame(Groups=0:3, col=c("grey80", "#87ffd5", "#47ad88", "#116349")) ### Legends - 修改部分 legend1 <- g_legend(ggplot(dfCol1, aes(x=2, y=1, fill=factor(Groups))) + geom_bar(stat="identity") + scale_fill_manual(values=dfCol1$col, name="short") + theme(legend.position="right", legend.text=element_text(size=7), legend.key.size=unit(0.4, 'cm'), # 设置图例标题左对齐 legend.title=element_text(hjust=0)) + guides(fill=guide_legend(title.position="top", title.hjust=0))) # 统一图例宽度 legend1 <- grid.grabExpr(grid.draw(legend1, vp=viewport(width=unit(2, "cm")))) legend2 <- g_legend(ggplot(dfCol2, aes(x=2, y=1, fill=factor(Groups))) + geom_bar(stat="identity") + scale_fill_manual(values=dfCol2$col, name="veryLongTitle") + theme(legend.position="right", legend.text=element_text(size=7), legend.key.size=unit(0.4, 'cm'), # 设置图例标题左对齐 legend.title=element_text(hjust=0)) + guides(fill=guide_legend(title.position="top", title.hjust=0))) # 统一图例宽度,和legend1保持一致 legend2 <- grid.grabExpr(grid.draw(legend2, vp=viewport(width=unit(2, "cm")))) ### Plots barPlot1 <- ggplot(dfCol1, aes(x=2, y=1, fill=factor(Groups))) + geom_bar(stat="identity") + scale_fill_manual(values=dfCol1$col, name="abc") + guides(fill="none") barPlot2 <- ggplot(dfCol2, aes(x=2, y=1, fill=factor(Groups))) + geom_bar(stat="identity") + scale_fill_manual(values=dfCol2$col, name="abc") + guides(fill="none") ##### Display plots ggarrange( grid.arrange(barPlot1, barPlot1, barPlot1, legend1, nrow=1, widths=c(1,1,1,0.8)), grid.arrange(barPlot2, barPlot2, barPlot2, legend2, nrow=1, widths=c(1,1,1,0.8)), nrow=2, align="v" )
关键修改点说明
- 图例标题左对齐:将
guide_legend的title.hjust设为0,同时在theme里设置legend.title=element_text(hjust=0),确保标题紧贴图例左侧。 - 统一图例宽度:使用
grid::viewport为两个图例设置相同的固定宽度(比如unit(2, "cm")),这样无论标题长短,图例的整体水平占位一致。 - 调整布局宽度比例:在
grid.arrange中通过widths参数指定绘图和图例的宽度比例,保证每行的绘图区域和图例区域对齐。
这样修改后,两个图例就会实现左对齐的效果,同时保持每行的绘图和图例布局协调。
内容的提问来源于stack exchange,提问作者Yacine Hajji
相关产品推荐
相关产品推荐

