How to add the prior distribution to the mcmc_area chart

Hi. This is more like a R and ggplot question, and because I am not good at making graphs.

I finished running a Stan model using cmdstan, and fit is the output object.

I want to plot the mcmc_areas graph for a parameter along with its prior distribution, which is normal(0,10) in this example

>posterior1 <- fit$draws(format="df")
>mcmc_areas(posterior1, pars = c("b2"), prob = 0.9) +
  stat_function(fun = dnorm, args = list(mean = 0, sd = 10))

This graph is not pretty. Is there a way to make it so?

The bayesplot outputs are just ggplot objects so you should be able to manipulate them the same way you would pretty much any other plot generated by that package.

Thanks for your reply. I am aware of the possibility and I even supplied my attempt in code. But the result is clearly not what one wants to see. I would appreciate it if you can provide any suggestion. Cheers.

In case it might be helpful, here’s an answer I wrote a while back that extracts prior and posterior draws and plots them on the same graph.

2 Likes

Thank you to your idea. I learned from your code and this is what I achieved for just one parameter.

posterior0 <- fit0$draws(format="df")

model_draws <-
  posterior0 %>%
  select(.chain, .iteration, .draw, starts_with("mu"))

S=500 #number of draws needed

plotting <- data.frame(mu=c(sample(model_draws$mu,S),
                rnorm(S,mean=0,sd=1)),
           group=c(rep('posterior',S),rep('prior',S)))

ggplot(data=plotting, aes(x=mu,colour=group)) +
  geom_density()

While this works, I would still prefer to see a way to add the prior distribution plot with mcmc_areas() or any of those functions in bayesplot package.