rggplot2rstan

Stack rstan::stan_dens() posterior densities on one figure without facets


I'm trying to recreate this figure the top left panel of this figure: enter image description here

In short I want to stack multiple posterior densities of a random effect on top of each other. I've looked at rstan::stan_dens() but it doesn't have any sort of add = TRUE argument. Is there a way to stack these posteriors quickly with a rstan plot function? Or should I just extract() the samples and plot it in ggplot the long way?

Some sample code I was playing with. Would be cool to stack the thetas.

library(rstan)
library(ggplot2)
example("read_stan_csv")
fit <- stan_demo("eight_schools") #select option 2 to temp load - takes some time

p <- stan_dens(fit, fill = NA, pars = "theta") + #can I stack these thetas easily?
      ggtitle("stack me please!")
p

plots this: enter image description here


Solution

  • You can do what rstan does and use the unexported function .make_plot_data, passing the result straight to ggplot. Here, I'll use the read_stan_csv example, but you should be able to get your own example working if you change pars to "theta"

    library(rstan)
    library(ggplot2)
    
    example("read_stan_csv")
    
    ggplot(rstan:::.make_plot_data(fit, pars = "z", TRUE, FALSE, FALSE)$samp,
           aes(value, group = parameter)) +
      geom_density() +
      theme_classic(base_size = 20)
    

    enter image description here