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