Difficulty getting a legend to add to my graph

Viewed 34

I have tried many ways to add a legend to the bottom two graphs but for some reason it either gives an error or doesn't show the legend.

Here is my code:

lg <- function(x, a = 1, b = 1){
  exp(a+b*x) / (1+exp(a+b*x))
}
plot(NA, xlim=c(-5,5), ylim=c(0,1), xlab = "x", ylab = "y", legend(2, 0.4, legend=c("b = 1", "b = 2", "b = 3", "b = 4", "b = 5"))
for (b in c(1:5)){
  curve(expr = lg(x, 1, b), from = -5, to = 5, n = 100, add= TRUE, col = b)
}
plot(NA, xlim=c(-5,5), ylim=c(0,1), xlab = "x", ylab = "y", legend(2, 0.4, legend=c("a = 1", "a = 2", "a = 3", "a = 4", "a = 5"))
for (a in c(1:5)){
  curve(expr = lg(x, a, 1), from = -5, to = 5, n = 100, add= TRUE, col = a)
}

Is there something wrong with my placement of the legend within the code?

1 Answers

Put legend function in new row without comma before. And close parenthesis of plot:

plot(NA, xlim=c(-5,5), ylim=c(0,1), xlab = "x", ylab = "y") 
legend(2, 0.4, legend=c("b = 1", "b = 2", "b = 3", "b = 4", "b = 5"))
     for (b in c(1:5)){
         curve(expr = lg(x, 1, b), from = -5, to = 5, n = 100, add= TRUE, col = b)
     }

enter image description here

same for plot2

plot(NA, xlim=c(-5,5), ylim=c(0,1), xlab = "x", ylab = "y") 
legend(2, 0.4, legend=c("a = 1", "a = 2", "a = 3", "a = 4", "a = 5"))
     for (a in c(1:5)){
         curve(expr = lg(x, a, 1), from = -5, to = 5, n = 100, add= TRUE, col = a)
     }

enter image description here

Related