PAYATHON 2026

在单图中合并两个模型的 epred_draws 预测抽样

数据小陈

结论:先给两个 epred_draws() 的结果各加一列来源,再用 dplyr::bind_rows() 合并,最后在 ggplot2 里把 color 和 fill 映射到来源列。为了让 prior 和 posterior 的比较更可靠,两边最好用完全相同的 newdata 网格;否则 x 轴采样点不一样,图形差异里就会混入采样点的影响。

推荐做法:统一 newdata 后合并

library(dplyr)
library(ggplot2)
library(tidybayes)

newdata <- tidyr::expand_grid(
  teci = seq(min(land3km$teci), max(land3km$teci), length.out = 50)
)

pred_info_teci4 <- mod_info_teci_PO4 |>
  epred_draws(newdata = newdata, ndraws = 200) |>
  mutate(model_type = 'prior')

post_info_teci4 <- mod_info_teci4 |>
  epred_draws(newdata = newdata, ndraws = 200) |>
  mutate(model_type = 'posterior')

combined <- bind_rows(pred_info_teci4, post_info_teci4) |>
  mutate(model_type = factor(model_type, levels = c('prior', 'posterior')))

ggplot(combined, aes(x = teci, y = .epred, color = model_type, fill = model_type)) +
  stat_lineribbon(alpha = 0.25, .width = c(0.5, 0.8, 0.95)) +
  scale_color_manual(values = c(prior = '#1b9e77', posterior = '#d95f02')) +
  scale_fill_manual(values = c(prior = '#1b9e77', posterior = '#d95f02')) +
  labs(
    x = 'teci',
    y = 'Predicted probability',
    color = 'Draw type',
    fill = 'Draw type'
  ) +
  theme_minimal()

如果想看单条 draw 的轨迹,而不是分位数带,可以把 stat_lineribbon() 换成 geom_line(),用 group = interaction(model_type, .draw) 让每条 draw 独立成线,再用 alpha 降低重叠造成的遮挡。

关于只拟合一次模型

可以,但要分清两种情况。sample_prior = 'only' 表示模型只从先验抽样,适合直接生成 prior-only 预测;sample_prior = 'yes' 表示同一个 brmsfit 里同时保存先验和后验抽样,这样能省去重复拟合。不过 epred_draws() 默认使用后验抽样,不会自动同时返回 prior 和 posterior。你需要显式提取先验期望预测,比如在支持该参数的版本中给 epred_draws() 或底层的 posterior_epred() 传入 prior = TRUE,或者用 prior_draws() 自己算。不同 brms/tidybayes 版本的参数可能不一样,用之前先看 ?epred_draws 或 args(brms::posterior_epred) 确认。

# 仅示意;请先确认当前版本支持 prior 参数
# prior_one <- mod_info_teci4 |>
#   epred_draws(newdata = newdata, ndraws = 200, prior = TRUE) |>
#   mutate(model_type = 'prior')
#
# post_one <- mod_info_teci4 |>
#   epred_draws(newdata = newdata, ndraws = 200) |>
#   mutate(model_type = 'posterior')

如果只是这次 prior 与 posterior 的对比,分别拟合两个模型更直观,也不容易把先验抽样和后验抽样混在一起;如果模型跑得很久,再考虑用 sample_prior = 'yes' 的单模型方案。

备注:内容仅供参考。