legend

legend(x, y=NULL, legend, …)
Add a legend to a plot.
  • x – Two options: (1) Use "topleft", "bottomright", etc. (2) Use an x-coordinate for the top-left corner of the legend. I generally prefer the first option.
  • y – If chose option (1) for x, then skip this argument. If used option (2), then specify the y-coordinate for the top-left corner of the legend.
  • legend – A character vector listing names or descriptions for the plotted characters and/or lines.
  • – Additional arguments that characterize how to distinguish between different plotting characters or lines in the plot. Use arguments like pch, col, lty, and/or lwd. These arguments should be input as vectors, where the vector elements correspond to the legend values.

Example. Stock return data were retrieved from a file called stocks.rda (download it here) and reformatted a little. Here the stock returns were included in the data, not the prices, so I backed-out to standardized prices by adding 1 and applying cumprod for each stock (Apple, Microsoft, and Google). Finally, the results are plotted and a legend was added.
> #==== Retrieve Data, Reverse Row Order ====#
> # http://rfunction.com/code/1203/stocks.rda
> load("stocks.rda")
> head(stocks)
                  AAPL         MSFT          GOOG
2012-03-01 0.003742349  0.017328292  0.0067124949
2012-02-29 0.013130125 -0.004079071 -0.0002263943
2012-02-28 0.018354382  0.016586922  0.0149021024
2012-02-27 0.006412588 -0.004129606 -0.0009673717
2012-02-24 0.011657855  0.003506535  0.0062529904
2012-02-23 0.006529705  0.003197953 -0.0030101655
> stocks <- stocks[nrow(stocks):1,]
> 
> #==== Convert Returns To Standardized Price ====#
> AAPL  <- cumprod(stocks[,"AAPL"]+1)
> MSFT  <- cumprod(stocks[,"MSFT"]+1)
> GOOG  <- cumprod(stocks[,"GOOG"]+1)
> dates <- as.Date(rownames(stocks))
> 
> col <- c(rgb(0.8, 0.3, 0.1),
+          rgb(0.1, 0.3, 0.9),
+          rgb(0.3, 0.8, 0.3))
> 
> # png("stocks.png")
> plot(dates, AAPL, type="l", col=col[1], xlab="",
+      ylab="Ratio to stock price at start of 2008")
> lines(dates, MSFT, col=col[2], lwd=1.5)
> lines(dates, GOOG, col=col[3], lwd=2)
> legend("topleft", col=col, lwd=c(1, 1.5, 2),
+        legend=colnames(stocks))
> # dev.off()

Other functions used in the example: load, as.Date, png.
Tip. Just a couple of the many additional arguments available in legend that might be of interest: fill, bg.

Leave a Reply