2014-01-24 52 views
-1

我想在ggplot 2中爲我的先前和後面創建一個圖例。我使用knitr,因此它需要能夠轉移到它上面,但這不應該是一個問題。 下面是我的代碼:如何在ggplot2中爲之前和之後創建圖例?

<<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

如果您將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")) 

相關問題