2014-09-20 196 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