How to display the legend of a bar plot in a colored box in R?

R ProgrammingServer Side ProgrammingProgramming

When we create a bar plot or any other plot with legend, the background of the legend is white but it can be changed to any color with the help of scales package. We can make changes in the legend of a plot using alpha in legend.background argument of theme function. This will help us to change the background color of the legend.


 Live Demo

> x<-c("0","100","150","200")
> y<-c(25,28,32,25)
> df<-data.frame(x,y)
> df


   x  y
1   0 25
2 100 28
3 150 32
4 200 25

Creating a bar plot with legend −

> library(ggplot2)
> ggplot(df,aes(x,y,fill=x))+geom_bar(stat="identity")


Changing the background color of the legend −

> library(scales)
> ggplot(df,aes(x,y,fill=x))+geom_bar(stat="identity")+theme(legend.background=element


Published on 04-Sep-2020 08:29:42