- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- 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.
Example
> x<-c("0","100","150","200") > y<-c(25,28,32,25) > df<-data.frame(x,y) > df
Output
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")
Output
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")))
Output
Advertisements