How to facet-wrap comparative density plots in R with ggplot

41 Views Asked by At

I have a dataset of different conditions with values of length. I can make histograms/density plots out of it and can facet wrap it for comparison to the control condition.

I can also make individual plots comparing the control to a specific condition (i.e. overlapping density plot with transparency). This helps me see the distribution of values for each condition compared to the control.

However, I would like to see the comparison for all conditions side by side such as when I use facetwrap.

For example, if this is my data in a dataset "test": enter image description here

This is how I made the density plot facet wrap:

test %>%
  ggplot(mapping = aes(x = Size, fill = Condition)) +
  geom_density(alpha = 0.2) +
  facet_wrap(vars(Condition))

This is my individual overlapped density plot (I create a new data set that only contains the 2 conditions I want to compare):

test_compare <- test %>% 
  filter(Condition == "Control" | Condition == "Condition 1")
test_compare %>%
  ggplot(mapping = aes(x = Size, fill = Condition)) +
  geom_density(alpha = 0.2)

Where the two overlap like this: enter image description here

I would like to have a grid where I can see each condition compared to the control. Is there a way to do this?

1

There are 1 best solutions below

2
mchen On

EDIT: This is essentially what is linked in the comments by @MrFlick

You should be able to create a second dataframe with the "control" data and add a second geom_density() call to add the control data independently of whatever gets faceted.

Reproducible Example since you didn't provide any data.

dat <- data.frame(Size = 0:100)

dat <- dat %>%
  mutate(Condition = case_when(Size >= 75 ~ "C1", 
                               Size >= 50 & Size < 75 ~ "C2",
                               Size >= 25 & Size < 50 ~ "C3",
                               Size >= 0 & Size < 25 ~ "Control",
                               TRUE ~ "NA"), 
         Control = case_when(str_detect(Condition, "Control") ~ "Control",
                             TRUE ~ "Sample"))

dat.control <- dat %>%
  select(Size, Control)

ggplot(dat %>% filter(Condition != "Control"), aes(x = Size)) +
  geom_density(data = dat.control %>% filter(Control == "Control"), aes(x = Size), alpha = 0.2, fill = "orange") +
  geom_density(alpha = 0.2, aes(fill = Condition)) +
  facet_wrap(~Condition)

enter image description here