xfim / ggmcmc

Graphical tools for analyzing Markov Chain Monte Carlo simulations from Bayesian inference
111 stars 31 forks source link

HPD intervals in density plots and traceplots #62

Closed lindeloev closed 5 years ago

lindeloev commented 6 years ago

It took me some time to figure out how to add HPD intervals to density plots. I think it would be great to have an argument like HPD=FALSE to ggs_density (horizontal) and ggs_traceplot (vertical).

Here you go for density:

# Functions to get HPD
hpd_lower = function(x, prob=0.95) HPDinterval(as.mcmc(x), prob=prob)[1]
hpd_upper = function(x, prob=0.95) HPDinterval(as.mcmc(x), prob=prob)[2]

# Make data for geom_segment to use
hpd_data = dplyr::group_by(my_ggs_data, Parameter) %>% 
  dplyr::summarize(x=hpd_lower(value), xend=hpd_upper(value))

# Density and HPD
ggplot(plot1_ggs, aes(x=value)) + 
  geom_density(aes(fill='gray', y=..scaled..)) + scale_fill_manual(values = "gray") +
  geom_segment(data=hpd_data, aes(x=x, xend=xend, y=0.01, yend=0.01), size=3) + 
xfim commented 5 years ago

Dear @lindeloev ,

Thank you for the code. I have adapted it (d4a2a2a71360046eefccb06fff8c24016dbcd575) and now the HDP band(s) are shown when using the argument hpd = TRUE in both geom_density() and geom_traceplot().