How to make legend key fill transparent in ggplot2 in R?
In this article, we will see how to make legend key fill transparent in ggplot2 in R Programming Language.
Note: Here we will be using a line graph, the same can be applied to any other plot.
Let us first draw a regular plot, so that the difference is apparent.
As you can see clearly in the above plot, Legend Keys have a grey background. So now we are going to convert it into transparent by using theme() function. theme() in itself is a very big function containing lots of theme elements that we can apply to the plot for making our plot look presentable. To change the background of Legend keys, we use legend.key, which specifies the background underneath legend keys.
Syntax : theme(legend.key)
- legend.key : For specify background underneath legend keys. we assign element_rect function as the value of it.
Return : Theme Of the plot
Further, we specify the element_rect() function as a value of legend.key, which is often used for backgrounds and borders. It also has some parameters for customization such as fill, color, size, and linetype but here for make fill the Legend Keys with transparent background, we will use only fill parameter out of them.
Syntax : element_rect(fill)
- fill : fill with color.
return : Modifications on backgrounds and borders.
theme(legend.key = element_rect(fill))