Adding vertical lines (i.e. *geom_vline*?) to multiple plots from *bayesplot* functions


I would like to add different vertical lines with respect to each plot output (essentially with respect to different mcmc parameters) from bayesplot’s mcmc_hist. How would I do this?

For example, suppose I have some mcmc output that is a 3-dimensional array (2000 iterations, 4 chains, 4 parameters)


and suppose I have these target parameters were used to generate the sample/data for my MCMC model

w_target <- c(0.14, 0.34, 0.41, 0.11)

Then, suppose I made a 2x2 histogram using bayesplot’s mcmc_hist function resulting in 4 plots for my 4 parameters:

mcmc_hist(w_array) # note this will plot a histogram of mcmc results with merged chains

How do I add vertical lines, each representing different values of w_target, with respect to each plot (with respect to each parameter)? I would like a 0.14 vertical line for the first plot, 0.34 vertical line for the second plot, 0.41 vertical line for the third plot, 0.11 vertical line for the fourth plot.

Obviously, if it was just one plot, I could just geom_vline(xintercept=#) and be done. I have a feeling this involves the usage of the facet_args argument in mcmc_hist, but I’m completely stumped. Later, I would also like to add numerous horizontal lines to my numerous trace plots or extend the code logic to other types of bayesplots


I’m not sure if there’s a built-in way to do this with mcmc_hist(), but you should be able to add it via regular ggplot approaches.

First, you’ll need to figure out the column name of the facet variable that the internal ggplot uses. If you save the histogram as my_hist, you’ll be able to inspect the facet names with my_hist$facets$params$facets.

Once you have that name (I’m going to assume it’s param), make a new data frame with columns param and x_line that matches each facet to the location of it’s vertical line. Then add geom_vline(aes(xintercept = x_line), data = my_line_data, inherit.aes = FALSE) to my_hist.

Ah I figured as much. Thank you.