0

I want to create a legend for my prior and posterior in ggplot 2. I'm using knitr so it needs to be able to transfer onto it but that shouldn't be a problem. Below is the code I have:

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

I've tried a few things but I can't figure out the best way. Thanks!

1 Answers1

0

If you put colour= inside the calls to aes(...), ggplot makes a color scale and creates a legend automatically.

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

jlhoward
  • 58,004
  • 7
  • 97
  • 140