使用ggplot与ggarrange时如何避免图例框被截断?
解决Mac上ggarrange合并图表后图例框右侧边框截断问题
这是Mac环境下ggpubr包的ggarrange函数在处理带边框的公共图例时的布局计算bug,单独绘图没问题,合并时就会截断右边框。试试下面几个可行的解决办法:
办法1:给图例框加右边内边距
手动给图例框增加右侧内边距,让布局计算时预留足够空间显示完整边框:
library(ggplot2) library(ggpubr) p1 <- ggplot(mtcars, aes(x = mpg, y = disp, color = as.factor(am))) + geom_point() + theme( legend.box.background = element_rect(color = "black", size = 1), legend.box.margin = margin(r = 5) # 增加右侧内边距,数值可按需调整 ) p2 <- ggplot(mtcars, aes(x = hp, y = disp, color = as.factor(am))) + geom_point() + theme( legend.box.background = element_rect(color = "black", size = 1), legend.box.margin = margin(r = 5) ) ggarrange(p1, p2, common.legend = T, legend = "right")
办法2:换用patchwork包合并图表
patchwork在图表布局和图例处理上比ggarrange更稳健,完全可以替代ggarrange的功能:
library(ggplot2) library(patchwork) p1 <- ggplot(mtcars, aes(x = mpg, y = disp, color = as.factor(am))) + geom_point() + theme(legend.box.background = element_rect(color = "black", size = 1)) p2 <- ggplot(mtcars, aes(x = hp, y = disp, color = as.factor(am))) + geom_point() + theme(legend.box.background = element_rect(color = "black", size = 1)) # 合并图表并统一收集图例到右侧 (p1 + p2) + plot_layout(guides = "collect") & theme(legend.position = "right")
办法3:手动调整图例宽度
先提取图例对象,手动加宽后再传入ggarrange:
library(ggplot2) library(ggpubr) p1 <- ggplot(mtcars, aes(x = mpg, y = disp, color = as.factor(am))) + geom_point() + theme(legend.box.background = element_rect(color = "black", size = 1)) p2 <- ggplot(mtcars, aes(x = hp, y = disp, color = as.factor(am))) + geom_point() + theme(legend.box.background = element_rect(color = "black", size = 1)) # 提取图例 leg <- get_legend(p1) # 手动加宽图例宽度,数值按需调整 leg$width <- unit(leg$width + unit(5, "pt"), "pt") # 合并时传入调整后的图例,同时隐藏子图自身的图例 ggarrange(p1 + theme(legend.position = "none"), p2 + theme(legend.position = "none"), legend.grob = leg, legend = "right")
内容的提问来源于stack exchange,提问作者J. Doe
相关产品推荐
相关产品推荐

