[R] legend in plot

Naresh Gurbuxani n@re@h_gurbux@n| @end|ng |rom hotm@||@com
Thu May 5 14:40:50 CEST 2022


Is it possible to define legend in the plot command?  That will ensure that legend is correctly associated with the points or lines in the plot. 

# I can do this
x <- seq(-3, 3, by = 0.01)
plot(x, x, type = "l")
lines(x, x^2, lty = 2, col = 2)
# In legend command, I need to remember that x^2 is lty = 2 and col = 2 
legend("bottomright", legend = c("x", expression(x^2)), lty = c(1, 2), col = c(1, 2), bty = "n")

# I want to do something like this
plot(x, x, type = "l", label = "x")
lines(x, x^2, lty = 2, col = 2, label = expression(x^2))
# legend command already knows the legend for each line
legend("bottomright", bty = "n")

Thanks,
Naresh


More information about the R-help mailing list