如何修改ggMarginal背景色以匹配ggplot主图背景?
解决ggExtra::ggMarginal边际图背景色与主图不统一的问题
使用ggExtra::ggMarginal()为ggplot添加侧边密度直方图时,边际图默认背景为白色,无法匹配主图设置的#fffdf7背景色,导致图表衔接处出现白色线条。以下是修复方案:
核心修改点
直接在ggMarginal()中通过theme参数传递与主图一致的背景色设置,覆盖默认主题的白色背景。
修改后的完整代码
library(tidyverse) library(readxl) library(summarytools) library(ggExtra) library(ggtext) tr <- ggplot(mtcars) + aes(x = mpg, y = disp, color = as.character(cyl), shape = as.character(cyl)) + geom_point(size = 3) + geom_smooth(method = "lm", se = TRUE, show.legend = FALSE, alpha = 0.1) + scale_color_manual(values = c("#325756FF", "#7D9FC2FF", "#C582B2FF", "#51806AFF", "#4D5F8EFF", "#A092B7FF")) + labs( title = "<i> Mtcars</i> Vizualization Project", subtitle = "Model for <b style='color:#325756FF'>4</b>, <b style='color:#7D9FC2FF'>6</b>, and <b style='color:#C582B2FF'>8</b> Cylinders", x = "MPG", y = "Dispersion", caption = "Sources: mtcars.", shape = "Cylinder", color = "Cylinder", fill = "Cylinder" ) + theme( legend.position = "bottom", legend.title = element_text( family = "", face = "bold", size = 16, color = "grey30" ), legend.background = element_blank(), legend.box.background = element_blank(), legend.key = element_blank(), text = element_text( family = "", face = "bold", size = 16, color = "grey30" ), plot.title = element_markdown( lineheight = 1.1, family = "", size = 20, face = "bold", hjust = 0.5, color = "grey30" ), plot.subtitle = element_markdown( family = "", size = 14, hjust = 0.5, face = "plain", color = "grey30" ), plot.caption = element_text( family = "", size = 10, face = "plain", color = "grey30" ), axis.text.x = element_text( angle = 0, face = "bold" ), axis.text.y = element_text( angle = 0, face = "bold" ), axis.ticks = element_blank(), axis.line = element_line( color = "#b4aea9" ), panel.grid = element_line( color = "grey95" ), panel.grid.minor = element_blank(), panel.grid.major = element_line( linetype = "solid" ), panel.background = element_rect( fill = "#fffdf7", color = "#fffdf7" ), plot.background = element_rect( fill = "#fffdf7", color = "#fffdf7" ) ) # 修改ggMarginal部分,添加theme参数匹配主图背景 tr %>% ggMarginal( groupColour = TRUE, groupFill = TRUE, # 传递自定义主题给边际图 theme = theme( panel.background = element_rect(fill = "#fffdf7", color = "#fffdf7"), plot.background = element_rect(fill = "#fffdf7", color = "#fffdf7"), # 可选:保持边际图的轴文本样式与主图一致 axis.text = element_text(face = "bold", color = "grey30"), axis.ticks = element_blank() ) )
说明
ggMarginal()默认使用ggplot的基础主题(白色背景),因此需要显式传递与主图完全一致的背景色设置。通过在ggMarginal的theme参数中指定panel.background和plot.background的填充色为#fffdf7,即可消除主图与边际图之间的白色衔接线条,实现整体背景统一。
内容的提问来源于stack exchange,提问作者M.Frumh
相关产品推荐
相关产品推荐

