R legend() Function - Adding Legends
The R legend() function is used to add a legend to a plot, helping readers identify different data series.
When a plot contains multiple sets of data, a legend is an essential element.
The syntax of the legend() function is as follows:
legend(x, y = NULL, legend, col, pch, lty, lwd, fill, title = NULL)
Parameter description:
x, yLegend position: keywords such as "topright" and "bottomleft", or coordinates.
legendLegend text labels.
colColors of each data series.
pchPoint symbol type.
ltyLine type.
Example
# Monthly sales trends of three product categories
month <- 1:6
product_a <- c(100, 120, 115, 135, 145, 160)
product_b <- c(85, 90, 95, 100, 105, 110)
product_c <- c(60, 70, 80, 75, 90, 88)
# Draw a line chart
plot(month, product_a, type = "o",
col = "steelblue", lwd = 2, pch = 16,
ylim = c(50, 170),
main = "Monthly sales trends of each product",
xlab = "Month", ylab = "Sales")
lines(month, product_b, type = "o",
col = "coral", lwd = 2, pch = 17)
lines(month, product_c, type = "o",
col = "seagreen", lwd = 2, pch = 18)
# Add a legend
legend("topleft",
legend = c("Product A", "Product B", "Product C"),
col = c("steelblue", "coral", "seagreen"),
pch = c(16, 17, 18),
lwd = 2,
title = "Product Category")
month <- 1:6
product_a <- c(100, 120, 115, 135, 145, 160)
product_b <- c(85, 90, 95, 100, 105, 110)
product_c <- c(60, 70, 80, 75, 90, 88)
# Draw a line chart
plot(month, product_a, type = "o",
col = "steelblue", lwd = 2, pch = 16,
ylim = c(50, 170),
main = "Monthly sales trends of each product",
xlab = "Month", ylab = "Sales")
lines(month, product_b, type = "o",
col = "coral", lwd = 2, pch = 17)
lines(month, product_c, type = "o",
col = "seagreen", lwd = 2, pch = 18)
# Add a legend
legend("topleft",
legend = c("Product A", "Product B", "Product C"),
col = c("steelblue", "coral", "seagreen"),
pch = c(16, 17, 18),
lwd = 2,
title = "Product Category")
Running the above code will display three sales line charts with a color-coded legend.
Other Extensions
R Language Examples