mjskay / tidybayes

Bayesian analysis + tidy data + geoms (R package)
http://mjskay.github.io/tidybayes
GNU General Public License v3.0
712 stars 59 forks source link

Trouble with multi condition posterior #262

Closed zhengchencai closed 4 years ago

zhengchencai commented 4 years ago

Hi there,

R blog twitter led me here. Thanks for making this beautiful visualization tool. I was trying to go through the tutorial and wondering how do we plot posterior with for instance two conditions. Imagine I have subject ID and experiment condition from a multi-normal fitting. If I'd like to plot condition_mean on all subjects under a specific condition let's say 1. I've tried the following code but it got dimension error, could you please help?

m %>% spread_draws(condition_mean[subid, 1]) %>% median_qi() %>% ggplot(aes(y = fct_rev(subid), x = condition_mean[,1])) + geom_pointintervalh()

another question is about the contrast plot, how can I specify the control? I read the help doc of compare_levels. it says to apply relevel() to by to set the control (reference) level. I've tried the following and also got error, let's see I'd like to use 2 as the control

m %>% spread_draws(condition_mean[condition]) %>% compare_levels(condition_mean, relevel(condition, 2) ) %>% ggplot(aes(y = condition, x = condition_mean)) + stat_halfeyeh()

Thanks a lot, Zhengchen

mjskay commented 4 years ago

For your first question, there are two issues:

My general suggestion would be get the first half of the code (up to the plot) working before playing with the ggplot part, that tends to make debugging easier. I think what you're trying to do should look like this: (Note: you mean need to run update.package() first to get the latest version of tidybayes, geom_pointintervalh() was recently deprecated --- see here).

m %>%
  spread_draws(condition_mean[subid, condition]) %>%
  filter(condition == 1) %>%
  median_qi() %>%
  ggplot(aes(y = fct_rev(subid), x = condition_mean)) +
  geom_pointinterval()

For your second question, the releveling should be done before the call to compare_levels. You also need to ungroup (since mutate does not allow you to modify grouping columns, of which condition is one). Something like this (again note use of stat_halfeye() instead of stat_halfeyeh() due to automatic orientation detection in the latest tidybayes):

m %>%
  spread_draws(condition_mean[condition]) %>%
  ungroup() %>%
  mutate(condition = relevel(factor(condition), 2))) %>%
  compare_levels(condition_mean, condition) %>%
  ggplot(aes(y = condition, x = condition_mean)) +
  stat_halfeyeh()