Question

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

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top