Get Started

Markov chain trace plots

A trace plot provides a visualization of a Markov chain's longitudinal behavior. Specifically, a trace plot for the \(m\) chain plots the observed chain value (y-axis) against the corresponding iteration number (x-axis).

You will construct trace plots of the \(m\) chain using two different approaches: by applying the built-in plot() function to the mcmc.list object sleep_sim and, for finer control over this graphic (and finer control over analyses in later chapters), by applying ggplot() to the data.frame object sleep_chains. Both sleep_sim and sleep_chains are in your workspace:

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)

This is a part of the course

“Bayesian Modeling with RJAGS”

View Course

Exercise instructions

  • Apply plot() to sleep_sim with density = FALSE to construct trace plots for the \(m\) and \(s\) chains. NOTE: The 10,000 recorded Iterations start after a "burn-in" period in which samples are discarded. Thus the Iterations count doesn't start at 1!

  • Apply ggplot() with a geom_line() layer to sleep_chains to re-construct the trace plot of the \(m\) chain.

  • Zoom in: construct a ggplot() trace plot of the first 100 iterations of the \(m\) chain.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# 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()
Edit and Run Code

This exercise is part of the course

Bayesian Modeling with RJAGS

AdvancedSkill Level
4.7+
7 reviews

In this course, you'll learn how to implement more advanced Bayesian models using RJAGS.

The two-parameter Normal-Normal Bayesian model provides a simple foundation for Normal regression models. In this chapter, you will engineer the Normal-Normal and define, compile, and simulate this model using rjags. You will also explore the magic of the Markov chain mechanics behind rjags simulation.

Exercise 1: The Normal-Normal modelExercise 2: Normal-Normal priorsExercise 3: Sleep study dataExercise 4: Insights from the prior and dataExercise 5: Simulating the Normal-Normal in RJAGSExercise 6: Define, compile, & simulate the Normal-NormalExercise 7: Posterior insights on sleep deprivationExercise 8: Markov chainsExercise 9: Storing Markov chainsExercise 10: Markov chain trace plots
Exercise 11: Markov chain density plotsExercise 12: Markov chain diagnostics & reproducibilityExercise 13: Multiple chainsExercise 14: Naive standard errorsExercise 15: Reproducibility

What is DataCamp?

Learn the data skills you need online at your own pace—from non-coding essentials to data science and machine learning.

Start Learning for Free