Using loops:
Example 1:two variables
mtcars$vs <- as.factor(mtcars$vs)
p <- unique(mtcars$vs)
g <- ggplot(mtcars, aes(x = mpg, fill = vs, colour = vs))
for (i in seq_along(p)) {
df <- mtcars %>% filter(vs == p[i])
g <- g + geom_density(alpha = .05) +
stat_function(data = df,
fun = dnorm,
args = list(mean = mean(df$mpg), sd = sd(df$mpg)))
}
g
Example 2: more than two variables
mtcars$cyl <- as.factor(mtcars$cyl)
p <- unique(mtcars$cyl)
g <- ggplot(mtcars, aes(x = mpg, fill = cyl, colour = cyl))
for (i in seq_along(p)) {
df <- mtcars %>% filter(cyl == p[i])
g <- g + geom_density(alpha = .05) +
stat_function(data = df,
fun = dnorm,
args = list(mean = mean(df$mpg), sd = sd(df$mpg)))
}
g
Scrappy solution: adding two layers
library(ggplot2)
mtcars$vs <- as.factor(mtcars$vs)
mt1 <- filter(mtcars, vs == 1)
mt0 <- filter(mtcars, vs == 0)
ggplot(mtcars, aes(x = mpg, fill = vs, colour = vs)) + geom_density(alpha = 0.1) +
stat_function(data = mt0, fun = dnorm,
args = list(mean = mean(mt0$mpg), sd = sd(mt0$mpg))) +
stat_function(data = mt1, fun = dnorm,
args = list(mean = mean(mt1$mpg), sd = sd(mt1$mpg)))
Output:
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…