R: overlay density plot with lines based on condition of a column

Viewed 407

I have a dataframe that consists of one column of conditions (strings) and multiple columns of number values. For each column, I would like to create an overlaid density plot, where each line represents a condition. I have found many solutions to overlay each column as one line on the same plot, but not how to create the lines by grouping based on conditions. Since this is a large dataset, I would rather not specify the groups manually.

condition c2 c3 c4
b 1 0 2
c 3 1 2
a 5 0 1
a 2 4 3
c 1 1 1
b 2 3 3
a 1 0 2
c 3 1 2
c 6 0 2
a 2 0 1
c 1 3 1
b 4 3 0

Using this example data I would like to have one density plot for each of columns 2-4. There should be 3 lines per plot (representing a, b and c).

Preferably I would like to do this with ggplot.

3 Answers

Another option is ggdensity

library(ggpubr)
out <- ggdensity(df, x = c("c2", "c3", "c4"), color = "condition",
         fill = "condition")
ggarrange(plotlist = out, ncol = 2, nrow = 2)

-output

enter image description here

data

df <- structure(list(condition = c("b", "c", "a", "a", "c", "b", "a", 
"c", "c", "a", "c", "b"), c2 = c(1L, 3L, 5L, 2L, 1L, 2L, 1L, 
3L, 6L, 2L, 1L, 4L), c3 = c(0L, 1L, 0L, 4L, 1L, 3L, 0L, 1L, 0L, 
0L, 3L, 3L), c4 = c(2L, 2L, 1L, 3L, 1L, 3L, 2L, 2L, 2L, 1L, 1L, 
0L)), class = "data.frame", row.names = c(NA, -12L))
library(tidyr)
library(ggplot2)

df %>% 
  pivot_longer(-condition) %>% 
  ggplot(aes(value, color = condition)) +
  geom_density() + 
  facet_wrap(~ name)

returns

enter image description here

Edit Thanks to Brenton M. Wiernik's comment, we could use scales = "free" to scale all plots seperately.

df %>% 
  pivot_longer(-condition) %>% 
  ggplot(aes(value, color = condition)) +
  geom_density(alpha = .3) +
  facet_wrap(~ name, scales = "free")

returns

enter image description here

ggplot(df, aes(x = value, fill = condition)) + 
    geom_density(alpha = 0.5) +
    facet_wrap(~name, scales = "free_x") +
    theme_classic()

enter image description here

Related