A legend helps explain what different colors or symbols mean in a plot. It makes charts easier to understand.
0
0
Legend control in R Programming
Introduction
When you have multiple groups or categories shown with different colors or shapes in a plot.
When you want to label lines or points in a graph so viewers know what each one represents.
When you create a bar chart with different colors for each bar group.
When you want to add clarity to a scatter plot with points of different colors.
When you want to customize the legend position or appearance to improve readability.
Syntax
R Programming
legend(x, y = NULL, legend, fill = NULL, col = NULL, pch = NULL, title = NULL, ...)
x and y specify the position of the legend on the plot.
legend is a character vector with labels for the legend.
Examples
Adds a legend at the top right with colored boxes for two groups.
R Programming
legend("topright", legend = c("Group A", "Group B"), fill = c("red", "blue"))
Places a legend at coordinates (1,1) with symbols for cats and dogs.
R Programming
legend(1, 1, legend = c("Cats", "Dogs"), col = c("black", "brown"), pch = c(1, 2))
Sample Program
This program plots two data series with different colors and symbols. The legend explains which color and symbol belong to each series.
R Programming
x <- 1:5 y1 <- c(2, 3, 5, 7, 11) y2 <- c(1, 4, 6, 8, 10) plot(x, y1, type = "b", col = "red", pch = 16, ylim = c(0, 12), ylab = "Value", xlab = "X") lines(x, y2, type = "b", col = "blue", pch = 17) legend("topright", legend = c("Series 1", "Series 2"), col = c("red", "blue"), pch = c(16, 17), title = "Legend")
OutputSuccess
Important Notes
You can change the legend position by using keywords like "topright", "bottomleft", or coordinates.
Use pch to set point symbols and col to set colors in the legend.
Adding a title to the legend helps clarify what the legend is about.
Summary
A legend explains colors or symbols in a plot.
Use legend() to add and customize legends in R plots.
Position, labels, colors, and symbols can all be controlled for clarity.