0

I am trying to add a legend to my R plot that has five lines which I built with the following code:

predictors=c(1,3,5,7,10,13)
meanvec25=c(23.642465, 14.590552, 11.480690, 10.919103, 9.365745, 10.265116)
meanvec100=c(22.668256, 12.220893, 10.598733, 9.768388, 9.710492, 10.139874)
meanvec500=c(21.864226, 12.290780, 9.879924, 9.598233, 9.856007, 9.629011)
meanvec2000=c(22.072814, 11.658274, 10.208657, 9.789607, 9.720389, 9.781965)
meanvec5000=c(22.006622, 11.535754, 10.172841, 9.664394, 9.722084, 9.814400)

plot(predictors,meanvec25,col="red",type="l")
lines(predictors,meanvec100,col="blue",type="l")
lines(predictors,meanvec500,col="green",type="l")
lines(predictors,meanvec2000,col="purple",type="l")
lines(predictors,meanvec5000,col="orange",type="l")

Then I typed this line to add a legend:

legend(1,95,legend=c("25 Trees","100 Trees","500 Trees","2000 Trees","5000 Trees"),col=c("red", "blue","green","purple","orange"), lty=c(1,1,1,1,1), cex=0.8)

Nothing is added to my graph, but no error messages appear either. I tried fiddling with the location numbers at the beginning of the function, but it doesn't seem to help. Why won't the legend appear?

Thanks!

Gretchen
  • 13
  • 3
  • 1
    Please update your question with a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). It's a lot easier for people to help you with a working example of the problem. – Mako212 Aug 17 '21 at 19:02
  • If you don't edit soon with something relevant, I propose this question will be closed. However, some things to help you resolve it yourself: `range(predictors)` must include 1, and `range(c(meanvec25,...,meanvec5000))` (use all vars) must include 95. Know that the default `legend` is aligned *down* and *right*, which means that if 1 is on the right side of your plot, you may not see it; and if 95 is towards the bottom of your plot, you may not see it. Good luck. – r2evans Aug 17 '21 at 19:23
  • Thank you all for your feedback. I hope my edits will make this reproducible. – Gretchen Aug 17 '21 at 19:38
  • 95 is above the plot region. Use `legend("topright", legend = c("25 Trees","100 Trees","500 Trees","2000 Trees","5000 Trees"),col=c("red", "blue","green","purple","orange"), lty=1, cex=0.8)` – G. Grothendieck Aug 17 '21 at 20:09
  • r2evans I see the issue. 95 was way out of my data range. Thank you! – Gretchen Aug 17 '21 at 20:10

0 Answers0