Home > OS >  R: Overlay density plots by condition and by average plot
R: Overlay density plots by condition and by average plot

Time:11-06

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

CodePudding user response:

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)
  • Related