Reputation: 395
I have a data frame that can be created as follows.
dat <- data.frame(dens = c(rnorm(50), rnorm(50, 10, 5), rnorm(50, 5, 1), rnorm(50, 3,2))
, group = rep(c("a", "b", "c", "d"), each = 50))
I am trying to compare the distribution of each possible pair of groups(a,b),(a,c), (a,d), (b,c), ... by plotting the distribution of each pair on top of each other.
I would like to have a sheet/frame in matrix form that have 16 slots so that each slot represent the distributions of let's say pair (a,b) and so on.
What I have now is the distribution plot of all 4 groups in one plot.
ggplot(dat, aes(x = dens, fill = group))+
geom_density(alpha = 0.5)
Do you have any idea if I can create the 4 * 4 sheet of plots?
Upvotes: 0
Views: 442
Reputation: 66890
Here's an approach that joins the data to itself, after nesting into groups. That way each group gets paired once with each other group (and itself), making it possible to plot each set against each other one in facets.
library(tidyverse)
dat_nested <- dat %>%
nest(data = c(dens)) %>% # Edit: better syntax to avoid warning msg
mutate(all = 1)
dat_nested %>%
full_join(dat_nested %>%
rename(group2 = group),
by = "all") %>%
unnest(cols = c(data.x, data.y), # updated to preferred tidyr 1.0.0 syntax
names_repair = make.unique) %>%
ggplot() +
geom_density(aes(x = dens, fill = group), alpha = 0.5) +
geom_density(aes(x = dens.1, fill = group2), alpha = 0.5) +
facet_grid(group ~ group2)
Upvotes: 4