0

I am able to create both density plots shown using the code provided. What I am hoping to do is create one graph combining the two. Essentially I want to overlay the black line on top of the plot colored by condition.

d1 <- ggplot(df, aes(x=a)) + geom_density()

d2 <- ggdensity(biolReps, x = "a", color = "b",fill = "b" d1

d2

keenan
  • 462
  • 3
  • 12
  • It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input that can be used to test and verify possible solutions. – MrFlick Nov 04 '21 at 03:18

1 Answers1

3

Is this what you're going for? I use after_stat here to scale down the conditional density plots to be comfortably lower than the total density. (which, being by definition less spiky, will tend to have lower peak densities than the conditional densities.)

ggplot(mtcars) +
  geom_density(aes(mpg)) +
  geom_density(aes(mpg, after_stat(count) * 0.01, 
                   group = cyl, fill = as.character(cyl)), alpha = 0.2)

enter image description here

If you want to convert this to a function, you could use something like the following. The {{ }} or "embrace" operator works to forward the variable names into the environment of the function. More at https://rlang.r-lib.org/reference/topic-data-mask-programming.html#embrace-with-

plot_densities <- function(df, var, group) {
  ggplot(df) +
    geom_density(aes( {{ var }} )) +
    geom_density(aes( {{ var }}, after_stat(count) * 0.01, 
                     group = {{ group }}, 
                     fill = as.character( {{ group }} )), alpha = 0.2)
}

plot_densities(mtcars, mpg, cyl)
Jon Spring
  • 55,165
  • 4
  • 35
  • 53
  • I am hoping to turn this into a function so I can reuse on multiple columns. I can get the total density plot this way using `ggplot(df) + geom_density(aes_string(column))` where column is passed to the function as "columnName" but I cannot get the aes_string to work with the second part of the code. Is this an easy fix? – keenan Nov 05 '21 at 23:49
  • I added an example of how to make this into a function. – Jon Spring Nov 06 '21 at 03:26