- Trending Categories
- Data Structure
- Operating System
- MS Excel
- C Programming
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to display the legend of a bar plot in a colored box in R?
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.
> 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 _rect(fill=alpha("green")))
- Related Articles
- How to create a colored box for base R plot?
- How to represent the legend in a plot created by using plot function with colored straight lines or stars in R?
- How to change legend values in a bar plot created by using ggplot2 in R?
- How to display x-bar in base R plot?
- How to cover legend in a box using ggplot2 in R?
- How to display text in bar plot in the middle using ggplot2 in R?
- How to add a legend on Seaborn facetgrid bar plot using Matplotlib?
- How to create colored barplot using ggplot2 without legend entries in R?
- How to reverse the bars of a bar plot a using ggplot2 in R?
- How to remove the boxes around legend of a plot created by ggplot2 in R?
- How to change the font size of legend in base R plot?
- How to change the background color of legend in base R plot?
- How to create horizontal lines for each bar in a bar plot of base R?
- How to remove the border of the legend of a chart created by plot function in R?
- How to adjust the size of a Matplotlib legend box?