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

如何用sjPlot的plot_model()实现带线型与彩色置信带的模型预测图

用sjPlot的plot_model()实现自定义线型+彩色置信带且图例同步显示

我明白你想通过plot_model()减少重复代码的需求,之前的尝试没成功主要是因为plot_model()默认的绘图映射逻辑和你预期的不一样。下面是解决方法和解释:

核心问题分析

  • 第一次尝试失败:plot_model(type="pred")默认给线条绑定的是color=group映射,没有设置linetype=group,所以单独加scale_linetype_manual()不会生效——因为没有对应的美学映射可以关联。
  • 第二次尝试的问题:colors="bw"确实能让线条变成黑白以便自定义线型,但默认情况下填充色(置信带)和线型的图例是分开的,而且填充图例不会显示对应的线型样式,导致图例信息不一致。

正确实现代码

library("ggplot2")
library("ggeffects")
library("sjPlot")
data(efc)
fit <- lm(neg_c_7 ~ c12hour * barthtot, data = efc)

# 用plot_model实现目标效果
plot_model(fit, type = "pred", terms = c("c12hour", "barthtot"), colors = "bw") +
  # 给线条添加linetype与group的映射
  aes(linetype = group) +
  # 自定义线型样式
  scale_linetype_manual(values = c("dotted", "dotdash", "longdash")) +
  # 给置信带设置彩色填充,统一图例名称
  scale_fill_brewer(palette = "Set1", name = "Total score BARTHEL INDEX") +
  # 让线条颜色和填充色对应,统一图例名称
  scale_color_brewer(palette = "Set1", name = "Total score BARTHEL INDEX") +
  # 合并图例,让填充、线条颜色、线型共用一个图例,同时给填充项添加线型标记
  guides(
    fill = guide_legend(override.aes = list(linetype = c("dotted", "dotdash", "longdash"))),
    color = guide_legend(override.aes = list(linetype = c("dotted", "dotdash", "longdash"))),
    linetype = guide_legend(name = "Total score BARTHEL INDEX")
  ) +
  # 自定义标题和坐标轴标签
  labs(
    title = "Predicted values of Negative impact with 7 items",
    x = "average number of hours of care per week",
    y = "Negative impact with 7 items"
  )

关键步骤说明

  1. 添加线型映射:通过aes(linetype = group)给线条绑定线型与分组的关系,这样scale_linetype_manual()才能生效。
  2. 统一颜色与图例:用scale_fill_brewer()和scale_color_brewer()让置信带填充色和线条颜色对应,并且统一图例名称,避免出现多个分散的图例。
  3. 合并图例:使用guides()调整图例,让填充、线条颜色和线型合并成一个图例,同时通过override.aes给填充的图例项加上对应的线型,确保图例能完整展示每个分组的样式信息。

这样就能实现和ggpredict()+ggplot()完全一致的效果,同时利用plot_model()简化批量模型的绘制流程。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 07:28:41