使用stat_function时向ggplot添加图例

时间:2014-09-20 16:45:25

标签: r ggplot2

我正在尝试向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作为另一个stackoverflow答案,但我无法显示一个图例。

参考答案 Using legend with stat_function in ggplot2

2 个答案:

答案 0 :(得分:2)

尝试:

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

答案 1 :(得分: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