马尔可夫链的轨迹图
"轨迹图"(trace plot)用于可视化马尔可夫链的纵向变化过程。具体来说,\(m\) 链的轨迹图会将观测到的链值(y 轴)与对应的迭代编号(x 轴)对应绘制。
您将用两种方式绘制 \(m\) 链的轨迹图:一是对 mcmc.list 对象 sleep_sim 使用内置函数 plot();二是为了更细致地控制图形(以及在后续章节中更细致地控制分析),对 data.frame 对象 sleep_chains 使用 ggplot()。sleep_sim 和 sleep_chains 都已在您的工作区中:
sleep_sim <- coda.samples(model = sleep_jags, variable.names = c("m", "s"), n.iter = 10000)
sleep_chains <- data.frame(sleep_sim[[1]], iter = 1:10000)
本练习是课程的一部分
使用 RJAGS 的贝叶斯建模
练习说明
对
sleep_sim使用plot(),并设置density = FALSE,以绘制 \(m\) 和 \(s\) 两条链的轨迹图。注意:记录的 10,000 个Iterations位于"燃烧期"(burn-in)之后,燃烧期的样本已被丢弃。因此Iterations计数并不从 1 开始!对
sleep_chains使用ggplot()并添加geom_line()图层,重现 \(m\) 链的轨迹图。放大查看:使用
ggplot()绘制 \(m\) 链"前 100 次迭代"的轨迹图。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Use plot() to construct trace plots of the m and s chains
# Use ggplot() to construct a trace plot of the m chain
ggplot(___, aes(x = ___, y = ___)) +
geom_line()
# Trace plot the first 100 iterations of the m chain
ggplot(___, aes(x = ___, y = ___)) +
geom_line()