Boxplots inside facet grid not behaving as expected

Hi all,

I have a tibble that is grouped and I want to show the distribution of each group on a facet plot using boxplots.

Here is a small synthetic representation of the tibble:

test <- tribble(
  ~condition, ~trial, ~ncount,
  "High", 1, 20L,
  "High", 1, 60L,
  "High", 2, 80L,
  "High", 2, 120L,
  "Low", 1, 90L,
  "Low", 1, 70L,
  "Low", 2, 20L,
  "Low", 2, 10L,
) %>% mutate_at(vars(condition, trial), factor) %>%
  group_by(condition, trial) %>%
 mutate(mean = mean(ncount))

image

Plotting the mean works fine with:

ggplot(test, 
       aes(x = condition, 
           y = mean, 
           group = trial)) +
  geom_point(size = 3) + 
  geom_line(color = "red") + 
  facet_grid(cols = vars(trial))

However, when I try to use boxplots instead to preserve the spread of the data instead of just using mean, only 2 boxplots are produced instead of 4. Condition (High, Low) is plotted together as 1 data set.

ggplot(test, 
       aes(x = condition, 
           y = ncount, 
           group = trial)) +
  geom_boxplot() +
  facet_grid(cols = vars(trial))

Any ideas what I am doing wrong here?

Regards,
Kenneth

Hi @bioinfguru

you have to change trial with the condition in the grouping

ggplot(test, 
       aes(x = condition, 
           y = ncount, 
           group = condition
           )) +
  geom_boxplot() +
  facet_grid(cols = vars(trial))

Excellent, wouldn't have thought of that. Thank you.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.