0

I have a for loop that creates a set of beta densities and looks something like this in my script.

x = seq(0,1,0.01)
alpha <- c(1,3,5,5,1,1,2,5,5,2)
beta <-  c(2,4,15,5,1,1,2,5,5,5)
color <- c("blue","green","pink","gray","brown","yellow","purple","skyblue","plum","tan")

plot(x,dbeta(x, alpha[1], beta[1]) / sum(x), type="l", col= color[1], xlab="x-axis", ylab="y-axis")
for(i in 2:10){
 lines(x,dbeta(x, alpha[i], beta[i]), type="l", col= color[i], pch="i")
}

I now want to create a legend at the bottom of the plot containing, the color of the line and the corresponding values from the alpha/beta vector. How do I achive this? All my attempts have failed until now...

user3347232
  • 407
  • 1
  • 7
  • 16
  • 1
    Maybe you can use the `legend` function : for example : `legend("bottom", legend = paste0(alpha, ";", beta), col = color, pch = 20)` – Julien Navarre Mar 01 '14 at 17:39
  • >All my attempts have failed until now... What have you tried? – EDi Mar 01 '14 at 17:51
  • I've been using the legend function wrong respectivly not knowing about the paste function. @JulienNavarre your code works. Unfortunatly the legend is displayed inside the plot and not at the bottom of it. What am I doing wrong? – user3347232 Mar 01 '14 at 18:02
  • possible duplicate of [Plot a legend outside of the plotting area in base graphics?](http://stackoverflow.com/questions/3932038/plot-a-legend-outside-of-the-plotting-area-in-base-graphics) – josliber Mar 01 '14 at 18:35

1 Answers1

0

Not base graphics, but ggplot was made for this.

params = data.frame(alpha,beta)
gg <- do.call(rbind,lapply(1:nrow(params),function(i)
                    cbind(i,x,y=dbeta(x,params[i,]$alpha,params[i,]$beta))))
gg <- data.frame(gg)
library(ggplot2)
ggplot(gg,aes(x,y,color=factor(i))) + 
  geom_line(size=1)+
  scale_color_manual("Alpha,Beta",
                     values=color,
                     labels=paste0("(",params$alpha,", ",params$beta,")"))+
  theme(legend.position="bottom")

Note that with your definitions of alpha and beta, plots 4, 8, and 9 are identical, and plots 5 and 6 are identical.

jlhoward
  • 58,004
  • 7
  • 97
  • 140