我想在ggplot 2中为我的先前和后期创建一个图例。我正在使用knitr所以它需要能够转移到它上面但这应该不是问题。 以下是我的代码:
<<echo=FALSE,message=FALSE,cache=FALSE,include=TRUE,fig.height=5,fig.pos="h!",
warning=FALSE>>=
require(ggplot2)
x <- seq(0, 1, len = 100)
y <- seq(0,6,len=100)
p <- qplot(x, geom = "blank")
Prior <- stat_function(aes(x = x, y = y), fun = dbeta, colour="red", n = 1000,
args = list(shape1 = 3, shape2 = 7))
Posterior <- stat_function(aes(x = x, y = ..y..), fun = dbeta, colour="blue",
n = 1000,args = list(shape1 = 7, shape2 = 23))
p + Prior + Posterior
@
我尝试了一些东西,但我找不到最好的方法。谢谢!
答案 0 :(得分:0)
如果您将colour=
放入aes(...)
的调用中,ggplot会自动生成色标并自动创建图例。
p <- qplot(x, geom = "blank")
Prior <- stat_function(aes(x = x, y = y,color="#FF0000"), fun = dbeta, n = 1000,
args = list(shape1 = 3, shape2 = 7))
Posterior <- stat_function(aes(x = x, y = y,color="#0000FF"), fun = dbeta,
n = 1000,args = list(shape1 = 7, shape2 = 23))
p + Prior + Posterior +
scale_color_discrete("Distibution",labels=c("Prior","Posterior"))