2014-09-20 176 views
0

我想添加一个图例ggplot区分模拟的正态分布和生成一个。下面是我的代码当使用stat_function添加图例ggplot

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

我尝试使用scale_colour_manual给出另一个答案计算器,但我不能让一个传奇展现出来。

参考答案 Using legend with stat_function in ggplot2

回答

1

尝试:

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

0

为了获得GGPLOT2你需要一个颜色可变的美学映射一个传说:

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