bayesplot
bayesplot copied to clipboard
Plotting estimates from multiple models
Hello,
I am interested in plotting posterior parameter estimates from multiple models in the same graph as this person describes here. Is there an easy way to do this?
Thanks!
Good question. We don't have a built-in way to do this at the moment, but it seems like a feature we should consider adding.
Until then here's one way to do it using bayesplot's mcmc_intervals_data()
function (which gives you the data bayesplot computes to pass to ggplot) in combination with a few ggplot functions:
# simulate having posteriors for two different models each with parameters beta[1],..., beta[4]
posterior_1 <- matrix(rnorm(4000), 1000, 4)
posterior_2 <- matrix(rnorm(4000), 1000, 4)
colnames(posterior_1) <- colnames(posterior_2) <- paste0("beta[", 1:4, "]")
# use bayesplot::mcmc_intervals_data() function to get intervals data in format easy to pass to ggplot
library(bayesplot)
combined <- rbind(mcmc_intervals_data(posterior_1), mcmc_intervals_data(posterior_2))
combined$model <- rep(c("Model 1", "Model 2"), each = ncol(posterior_1))
# make the plot using ggplot
library(ggplot2)
theme_set(bayesplot::theme_default())
pos <- position_nudge(y = ifelse(combined$model == "Model 2", 0, 0.1))
ggplot(combined, aes(x = m, y = parameter, color = model)) +
geom_point(position = pos) +
geom_linerange(aes(xmin = ll, xmax = hh), position = pos)
That makes a plot that looks like this:
Yes, that works. Thanks for your quick response!
Ok great glad that works! I'll leave this open since this seems like a useful feature to add to the package instead of requiring this workaround.
Hi I was wondering if there was a way to achieve a similar plot but for density plots? I'm not entirely sure how to use the data from mcmc_areas_data in ggplot to use a similar workaround.