Search code examples
rggplot2rstan

Changing the title of individual plots within a panel of traceplots in ggplot/stan


I am wondering, is there any way to change the titles of the individual plots in a traceplot in rstan/ggplot without having to change the names of the variables themselves?

See the following model and mcmc chains

dList <- list(gIndex = rep(1:2,times=20), nG=2, score = rnorm(40, c(0,7), 1), N = 40)
mc <- "
  data{
  int N;
  int nG;
  int gIndex[N];
  real score[N];
  }
  parameters{
  vector[nG] a;
  real sigma;
  }
  model{
  score ~ normal(a[gIndex], sigma);
  }
"
mod <- stan_model(model_code = mc) # compiles model
fit <- sampling(mod, data = dList, warmup = 1e3, iter = 2e3, chains = 3)
tp <- stan_trace(fit, pars = "a") 
tp

enter image description here

I would like to change the names of the original plots a[1] and a[2] to Treatment and Placebo (for example).


Solution

  • Found out how to do this. The bayesplot package allows the object x to be a 3d-array instead of a stanfit object, so we can change the fit object to an array

    fitArray <- as.array(fit)[,,-4] # remove the superfluous `_lpd` chain
    dim(fitArray)
    # [1] 1000    3    3
    

    Then rename the dimensions of the array

    dimnames(fitArray)[[2]] <- c("chain1", "chain2", "chain3")
    dimnames(fitArray)[[3]] <- c("treatment", "placebo", "sigma")
    dimnames(fitArray)
    
    # $iterations
    # NULL
    
    # $chains
    # [1] "chain1" "chain2" "chain3"
    
    # $parameters
    # [1] "treatment" "placebo"   "sigma" 
    

    Now we can use the mcmc_trace function in the bayesplot package

    library(bayesplot)
    mcmc_trace(fitArray)
    

    enter image description here

    Voila!