You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用plot_model()修改主题/美学时返回NULL的问题求助

解决sjPlot::plot_model()预测图无法叠加ggplot美学设置的问题

问题根源

当使用plot_model(lm_mod, type="pred")且模型包含多个自变量时,函数返回的是ggpubr::ggarrange对象(多个ggplot子图的组合),而非单一ggplot对象。直接用+叠加ggplot的主题/美学设置会因对象类型不匹配返回NULL。

解决方案

1. 仅绘制单个预测变量的图(返回单一ggplot对象)

指定terms参数只生成单个变量的预测图,此时返回的是标准ggplot对象,可正常叠加任何ggplot语法:

prediction <- plot_model(lm_mod, 
                         type="pred", 
                         show.data=TRUE,
                         dot.size = 1,
                         terms = "var1"  # 指定要绘制的单个自变量
                         )

# 正常调整美学与坐标轴
prediction + 
  theme(text=element_text(size=22),  
        axis.title = element_text(size=28, face="bold"),  
        axis.text = element_text(size=24), 
        axis.line = element_line(colour = "black", size = 1, linetype = "solid"),
        plot.title = element_text(size=28, face="bold", vjust=2, hjust=0.5)) +
  coord_cartesian(ylim = c(0, 100))  # 调整坐标轴范围(不删除数据)

2. 绘制多个预测变量的图(组合图)

方法一:使用sjPlot内置参数调整(推荐)

sjPlot提供了大量内置参数用于自定义图形,无需依赖ggplot的theme:

prediction <- plot_model(lm_mod, 
                         type="pred", 
                         show.data=TRUE,
                         dot.size = 1,
                         # 文字样式设置
                         axis.title.size = 28,
                         axis.title.fontface = "bold",
                         axis.text.size = 24,
                         plot.title.size = 28,
                         plot.title.fontface = "bold",
                         plot.title.align = 0.5,
                         # 坐标轴范围设置
                         axis.lim = list(c(0, 100), c(0, 100))  # 按子图顺序指定x/y轴范围
                         )

方法二:提取子图后单独调整再重组

如果必须使用ggplot的theme语法,可先提取所有子图,逐个调整后重新组合:

# 查看对象类型确认是ggarrange
class(prediction)

# 提取所有子图
plot_list <- prediction$plots

# 给每个子图添加自定义主题
plot_list <- lapply(plot_list, function(p) {
  p + theme(text=element_text(size=22),  
            axis.title = element_text(size=28, face="bold"),  
            axis.text = element_text(size=24), 
            axis.line = element_line(colour = "black", size = 1, linetype = "solid"),
            plot.title = element_text(size=28, face="bold", vjust=2, hjust=0.5)) +
    coord_cartesian(ylim = c(0, 100))
})

# 重新组合子图(根据子图数量调整行列)
library(ggpubr)
ggarrange(plotlist = plot_list, ncol = 2, nrow = 2)

验证对象类型

在调整前可先检查plot_model返回的对象类型:

class(prediction)
  • 输出为gg:单一ggplot对象,可直接用+叠加设置
  • 输出为ggarrange:组合图,需用上述方法二处理

内容的提问来源于stack exchange,提问作者lisaohhh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 03:08:16