I'm trying to recreate this figure the top left panel of this figure:
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 theta
s.
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
CodePudding user response:
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)