The “traceplot” Function in R

  • Package: rstan

  • Purpose: Visualizes traceplots of MCMC samples from a Stan model

  • General class: Bayesian inference

  • Required argument(s):

    • object: The result of fitting a Stan model using functions like stan_model.

  • Notable optional arguments:

    • pars: A character vector specifying the parameters to plot. If not specified, all parameters are plotted.

    • inc_warmup: Logical. If TRUE, includes the warmup samples in the traceplot. The default is FALSE.

    • nrow and ncol: Additional arguments passed to facet_wrap for arranging multiple plots.

  • Example:

  • # Load the rstan library
    library(rstan)

    # Define the Stan model code
    model_code <- '
    data {
    int<lower=0> N;
    real y[N];
    }
    parameters {
    real mu;
    real<lower=0> sigma;
    }
    model {
    y ~ normal(mu, sigma);
    }
    '

    # Compile the Stan model
    model <- stan_model(model_code = model_code)

    # Fit the Stan model
    N <- 100
    fit <- sampling(model, data = list(N = N, y = rnorm(N)))
    summary(fit)

    # Visualize traceplots
    traceplot(fit, pars = c("mu", "sigma"))

  • This example demonstrates how to use the “traceplot” function from the rstan package to visualize traceplots of MCMC samples from a compiled Stan model. The function requires the result of fitting a Stan model (stanfit object) as input and allows specifying optional arguments like the parameters to plot and whether to include warmup samples in the plot.

Previous
Previous

The “stan_hist” Function in R

Next
Next

The “optimizing” Function in R