Changing key style and changing legend color
We can change the key style of the legend and legend color using the theme function and providing legend.key as an argument. The legend.key argument is equal to the element_rect function which contains “color” for the outline color of the legend keys and “fill” for the inside color of the keys as its arguments. The as.factor() function will be used for the color argument to convert a vector or column from numeric to factor.
Example: R program change key style and legend color
R
library (ggplot2) data ( "USArrests" ) head (USArrests) # Plot the data plt <- ggplot (USArrests, aes (Murder, Assault, colour = as.factor (UrbanPop))) + geom_point ()+ theme (legend.key = element_rect ( color = "black" , fill = "light blue" )) plt |
Output :
Example 2: R program change key style and legend color
R
library (ggplot2) data ( "USArrests" ) head (USArrests) # Plot the data plt <- ggplot (USArrests, aes (Murder, Assault, colour = as.factor (UrbanPop))) + geom_point ()+ theme (legend.key = element_rect ( color = "white" , fill = "black" )) plt |
Output :
Working with Legends in R using ggplot2
A legend in a plot helps us to understand which groups belong to each bar, line, or box based on its type, color, etc. We can add a legend box in R using the legend() function. These work as guides. The keys can be determined by scale breaks. In this article, we will be working with legends and associated customization using ggplot2 in R programming language.
Syntax :
legend(x, y = NULL, legend, fill = NULL, col = par(“col”), border = “black”, lty, lwd, pch)