Following with the answer to my previous question, let's say that I am plotting density curves by group with ggplot
and I want to produce the corresponding normal curve for each group (with their corresponding means and standard deviations).
What I tried first was
library(ggplot2)
mtcars$vs <- as.factor(mtcars$vs)
ggplot(mtcars,aes(x=mpg, fill = vs, colour = vs)) + geom_density(alpha = 0.1) +
stat_function(fun = dnorm, args = list(mean = mean(mtcars$mpg), sd = sd(mtcars$mpg)))
but it produces a unique normal curve. Then I found in this question (whose answer I don't see how can help me), that stat_function
understands group
aesthetics, so I tried
ggplot(mtcars,aes(x=mpg, fill = vs, colour = vs)) + geom_density(alpha = 0.1) +
stat_function(aes(group = vs), fun = dnorm, args = list(mean = mean(mtcars$mpg), sd = sd(mtcars$mpg)))
but plot does not change. So how can I tell to stat_function
that I want the arguments should be taken for each vs
-group? I also expect the colour of each of these normal curves would be the same that (or related to) the mpg
curve colour of the same group.
I had also tried with
library(dplyr)
ggplot(mtcars %>% group_by(vs),...
but it had no effect.
Thanks!
See Question&Answers more detail:os