ggarrange修改共享图例背景及删除图表间白色边框方案咨询
ggarrange合并图表统一藏蓝色背景的极简实现方案
无需更换依赖包或重写大量代码,仅需在原有代码基础上补充3处配置即可实现所有需求,改动逻辑如下:
- 给每个子图的
theme添加plot.margin参数,消除子图四周默认的白色空白边距,可根据需求微调边距数值,只要背景统一就不会出现白边 - 给每个子图的
theme添加图例背景相关配置,ggarrange提取的共享图例会继承子图的图例样式,直接从根源修改即可去除图例的白色外框、设置藏蓝色背景 - 原有代码中
bgcolor("#140F4B") + border("#140F4B")的配置已经可以实现合并后整体画布的藏蓝色背景,无需额外调整
完整修改后的代码如下:
library(ggplot2) library(ggpubr) df <- data.frame(supp=rep(c("VC", "OJ"), each=3), dose=rep(c("D0.5", "D1", "D2"),2), len=c(6.8, 15, 33, 4.2, 10, 29.5)) cols <- c("VC" = "#0FC9F7", "OJ" = "#1010EB") p1 <- ggplot(df, aes(x=dose, y=len, color=factor(supp))) + geom_line(aes(group = supp)) + theme( plot.title = element_text(hjust = 0.5), panel.background = element_rect(fill = "#140F4B", colour = "#140F4B", size = 0.5, linetype = "solid"), panel.grid.major = element_blank(), panel.grid.minor = element_blank(), plot.background = element_rect(fill = "#140F4B"), text = element_text(colour = "white"), axis.line = element_line(colour = "white"), axis.text = element_text(colour = "white"), # 新增:消除子图边距 plot.margin = unit(rep(0,4), "pt"), # 新增:设置图例背景为藏蓝色、去除边框 legend.background = element_rect(fill = "#140F4B", color = NA), legend.box.background = element_rect(fill = "#140F4B", color = NA) ) + scale_color_manual(values = cols, name = "supp", breaks=c("VC", "OJ"), labels=c("VC", "OJ")) p2 <- ggplot(df, aes(x=dose, y=len, color=factor(supp))) + geom_line(aes(group = supp)) + theme( plot.title = element_text(hjust = 0.5), panel.background = element_rect(fill = "#140F4B", colour = "#140F4B", size = 0.5, linetype = "solid"), panel.grid.major = element_blank(), panel.grid.minor = element_blank(), plot.background = element_rect(fill = "#140F4B"), text = element_text(colour = "white"), axis.line = element_line(colour = "white"), axis.text = element_text(colour = "white"), # 新增:消除子图边距 plot.margin = unit(rep(0,4), "pt"), # 新增:设置图例背景为藏蓝色、去除边框 legend.background = element_rect(fill = "#140F4B", color = NA), legend.box.background = element_rect(fill = "#140F4B", color = NA) ) + scale_color_manual(values = cols, name = "supp", breaks=c("VC", "OJ"), labels=c("VC", "OJ")) plots <- list(p1, p2) combined_plots <- ggpubr::ggarrange(plotlist = plots, ncol = 2, nrow = 1, align = "hv", common.legend = TRUE, legend = "bottom") #Annotate plot combined_plots <- annotate_figure( combined_plots, top = text_grob(paste0("Example"), size = 18, color = "white") ) + bgcolor("#140F4B")+ border("#140F4B") # 查看效果 print(combined_plots)
内容的提问来源于stack exchange,提问作者Dr Wampa
相关产品推荐
相关产品推荐

