很难将图例添加到我的图表中

Difficulty getting a legend to add to my graph

我尝试了很多方法来为底部的两个图表添加图例,但由于某种原因,它要么给出错误,要么不显示图例。

这是我的代码:

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

我在代码中放置图例的位置有问题吗?

legend 函数放在新行中,前面没有逗号。 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)
     }

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