legend() Function in detail
The legend() function in R is used to add legends to an existing plot. A legend is an area within the graph plot that describes the elements of the plot. The legend helps visualize statistical data effectively.
Syntax:
legend(x, y, legend, fill, col, bg, lty, cex, title, text.font)
Parameters:
- x and y: Coordinates used to position the legend.
- legend: Text for the legend.
- fill: Colors used for filling the boxes in the legend.
- col: Colors of lines.
- bg: Background color for the legend box.
- title: Optional title for the legend.
- text.font: Integer specifying the font style of the legend (optional).
Returns:
A legend added to the plot.
Example 1: Basic Usage of legend()
# Generate some data
x <- 1:10
y1 <- x * x
y2 <- 2 * y1
# Create a plot with two lines
plot(x, y1, type = "b", pch = 19, col = "blue", xlab = "X", ylab = "Y")
lines(x, y2, pch = 22, col = "red", type = "b", lty = 6)
# Add a basic legend
legend("topright", legend = c("Line A", "Line B"), col = c("blue", "red"), lty = 1:2)
Output:

Example 2: Adding Title, Font, and Background Color to Legend
makePlot <- function(){
x <- 1:10
y1 <- x * x
y2 <- 2 * y1
plot(x, y1, type = "b", pch = 19, col = "blue", xlab = "X", ylab = "Y")
lines(x, y2, pch = 22, col = "red", type = "b", lty = 6)
}
makePlot()
# Add a legend with customization
legend(1, 95, legend = c("Curve A", "Curve B"), col = c("blue", "red"), lty = 1:2, cex = 0.9,
title = "Graph Types", text.font = 6, bg = "lightgray")
Output:

Example 3: Modifying Legend Box Border
makePlot <- function(){
x <- 1:10
y1 <- x * x
y2 <- 2 * y1
plot(x, y1, type = "b", pch = 22, col = "blue", xlab = "X", ylab = "Y")
lines(x, y2, pch = 18, col = "red", type = "b", lty = 4)
}
# Change the border of the legend
makePlot()
legend(1, 100, legend = c("Curve A", "Curve B"), col = c("blue", "red"), lty = 1:2, cex = 0.8,
box.lty = 4, box.lwd = 2, box.col = "blue")
Output:

Example 4: Removing the Legend Border
makePlot <- function(){
x <- 1:10
y1 <- x * x
y2 <- 2 * y1
plot(x, y1, type = "b", pch = 22, col = "blue", xlab = "X", ylab = "Y")
lines(x, y2, pch = 18, col = "red", type = "b", lty = 4)
}
# Remove legend border using box.lty = 0
makePlot()
legend(2, 100, legend = c("Curve A", "Curve B"), col = c("blue", "red"), lty = 1:2, cex = 0.8, box.lty = 0)
Output:

Example 5: Creating a Horizontal Legend with Different Symbols
makePlot()
# Add a horizontal legend with different symbols
legend("bottom", legend = c("Curve A", "Curve B"), col = c("blue", "red"), lty = 1:2, pch = c(19, 22), horiz = TRUE)
Output:

Leave a Reply