使用ggeffects绘制三向交互图时主题修改无法作用于所有分面
解决ggeffects多子图主题仅作用于单个分面的问题
当使用ggeffects绘制包含4个terms的交互图时,plot()返回的是多个独立ggplot对象的组合体,直接用+添加主题只会作用于最后一个子图。以下是两种可行的解决方法:
方法1:预先设置ggeffects全局主题
通过ggeffects::set_theme()定义默认主题,让所有子图生成时自动应用该主题:
library(ggeffects) library(ggplot2) dat_iris <- iris dat_iris$Petal.Size <- ifelse(dat_iris$Petal.Length <= 3, "small", "big") model_iris <- glm(Sepal.Length ~ Sepal.Width*Species + Petal.Width + Petal.Size, data = dat_iris) # 定义自定义主题 custom_theme <- theme_minimal() + theme(panel.grid.major = element_line(color = "#E5E5E5", linetype = "dashed", linewidth = 0.3), panel.background = element_rect(fill = "white", color = NA), plot.title = element_blank(), legend.title = element_text(face = "bold", size = 9), legend.text = element_text(size = 9), legend.position = "right", axis.title.x = element_text(face = "bold", size = 9), axis.title.y = element_text(face="bold", size = 9), strip.background = element_rect(fill = "#F0F0F0", color = NA), strip.text = element_text(face = "bold", size = 9)) # 将自定义主题设为ggeffects默认主题 set_theme(custom_theme) # 生成图形并添加其他标注、刻度设置 gg_iris <- plot(ggpredict(model_iris, terms=c("Sepal.Width", "Species", "Petal.Width", "Petal.Size")), colors = c("#190C3EFF", "#9C2964FF", "#F8870EFF")) + xlab("Sepal Width") + ylab("Sepal Length") + guides(color = guide_legend("Species"), fill = guide_legend("Species")) + scale_y_continuous(breaks = 4:8) + scale_x_continuous(breaks = 2:5) gg_iris
方法2:遍历子图逐个应用主题
将组合图拆分为单个ggplot对象,逐个修改后重新拼接:
library(ggeffects) library(ggplot2) library(patchwork) dat_iris <- iris dat_iris$Petal.Size <- ifelse(dat_iris$Petal.Length <= 3, "small", "big") model_iris <- glm(Sepal.Length ~ Sepal.Width*Species + Petal.Width + Petal.Size, data = dat_iris) # 生成原始组合图 gg_iris <- plot(ggpredict(model_iris, terms=c("Sepal.Width", "Species", "Petal.Width", "Petal.Size")), colors = c("#190C3EFF", "#9C2964FF", "#F8870EFF")) # 遍历每个子图,应用主题和其他设置 modified_plots <- lapply(gg_iris, function(p) { p + xlab("Sepal Width") + ylab("Sepal Length") + guides(color = guide_legend("Species"), fill = guide_legend("Species")) + theme_minimal() + theme(panel.grid.major = element_line(color = "#E5E5E5", linetype = "dashed", linewidth = 0.3), panel.background = element_rect(fill = "white", color = NA), plot.title = element_blank(), legend.title = element_text(face = "bold", size = 9), legend.text = element_text(size = 9), legend.position = "right", axis.title.x = element_text(face = "bold", size = 9), axis.title.y = element_text(face="bold", size = 9), strip.background = element_rect(fill = "#F0F0F0", color = NA), strip.text = element_text(face = "bold", size = 9)) + scale_y_continuous(breaks = 4:8) + scale_x_continuous(breaks = 2:5) }) # 重新拼接子图 wrap_plots(modified_plots)
原理说明
当ggpredict指定4个terms参数时,plot()会生成对应数量的独立ggplot对象并打包为列表/特殊组合体。常规的ggplot2语法+只能对单个ggplot对象生效,因此直接添加主题只会作用于最后一个子图。上述两种方法分别通过全局预设主题、逐个修改子图的方式,确保所有分面都应用指定的主题样式。
内容的提问来源于stack exchange,提问作者becbot
相关产品推荐
相关产品推荐

