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

如何用rstan堆叠theta后验密度图?stan_dens无add参数的解决办法

解决方法

快速堆叠法:用bayesplot包(rstan生态工具)

rstan::stan_dens()确实没有add=TRUE参数,但同生态的bayesplot包提供了更灵活的mcmc_dens()函数,能直接实现无分面的堆叠密度图,无需手动提取样本:

library(bayesplot)
# 假设你的stan拟合结果对象是fit,theta有K个维度
mcmc_dens(fit, pars = paste0("theta[", 1:5, "]"), facet = FALSE)
  • pars指定要绘制的theta参数(示例为theta[1]到theta[5],可根据实际维度调整)
  • facet = FALSE会把所有参数的密度曲线叠在同一张图中,自动用不同颜色区分

自定义绘图法:extract后用ggplot手动绘制

如果需要对图形样式做高度定制,可提取样本后用ggplot实现:

library(ggplot2)
library(rstan)
library(reshape2)

# 从拟合结果中提取theta的后验样本
theta_samples <- extract(fit, pars = "theta")[[1]]
# 将宽格式样本转为ggplot需要的长格式
theta_df <- melt(theta_samples, varnames = c("迭代", "theta编号"), value.name = "后验值")

# 绘制堆叠密度图
ggplot(theta_df, aes(x = 后验值, color = factor(theta编号))) +
  geom_density(linewidth = 1) +
  labs(x = "Theta后验值", color = "Theta编号") +
  theme_bw()

两种方法都能实现你要的无分面堆叠效果,前者快速便捷,后者自由度更高。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 06:50:24