1

I'm trying to add a legend to ggplot to differentiate between a simulated normal distribution and a generated one. Below is my code

set.seed(1)
lambda = .2
n = 40
sim = 10000
means = replicate(sim, expr = mean(rexp(n,lambda)))
ggplot(data.frame(means), aes(x=means)) + 
           geom_density() + 
           stat_function(fun = dnorm, color = "blue", 
                         arg = list(mean = 1/lambda, sd=sqrt(lambda^-2/n))) + 
           scale_colour_manual("Legend title", values = c("red", "blue"))

Rplot

I tried using scale_colour_manual as given another stackoverflow answer but I can't get a legend to show up.

Reference answer Using legend with stat_function in ggplot2

Community
  • 1
  • 1
canyon289
  • 3,355
  • 4
  • 33
  • 41

2 Answers2

2

Try:

set.seed(1)
lambda = .2
n = 40
sim = 10000
newvar = rnorm(sim, mean = 1/lambda, sd=sqrt(lambda^-2/n) )
means = replicate(sim, expr = mean(rexp(n,lambda)))
ddf = data.frame(means, newvar)
mm = melt(ddf)
ggplot(mm) +geom_density( aes(value, group=variable, color=variable) )

enter image description here

rnso
  • 23,686
  • 25
  • 112
  • 234
0

In order to get a legend in ggplot2 you need to map a color variable in the aesthetics:

ggplot(data.frame(means), aes(x = means)) + 
  geom_density(aes(color = "a")) + 
  stat_function(fun = dnorm, aes(color = "b"), 
                arg = list(mean = 1/lambda, sd = sqrt(lambda^-2/n))) + 
  scale_colour_manual("Legend title", values = c("a" ="red","b" = "blue"))

resulting plot

Roland
  • 127,288
  • 10
  • 191
  • 288