- 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 change the color of bars of a bar plot using ggplot2 in R?
The default color of the bars created by using ggplot2 package is grey but we can change that color to any depending on our interest. This change is highly required in professions such as academic writing and analytics because everyone wants to look at attractive images. They are not meant to be useful if you just want to learn the concept but when it comes to practical, you need to do it as attractive images gets more attention, thus, they become memorable. To change the color of the bars in ggplot2, we can use fill argument of geom_bar function.
Example
Consider the below data frame −
> Class<-c("A","B","C","D") > Frequency<-c(45,35,39,51) > df<-data.frame(Class,Frequency) > df
Output
Class Frequency 1 A 45 2 B 35 3 C 39 4 D 51
Creating a bar plot without specifying bar colors −
> library(ggplot2) > ggplot(df,aes(Class,Frequency))+geom_bar(stat='identity')
Output
Changing the color of bars in the bar plot −
> ggplot(df,aes(Class,Frequency))+geom_bar(stat='identity',fill="red")
Output
> ggplot(df,aes(Class,Frequency))+geom_bar(stat='identity',fill="blue")
Output
> ggplot(df,aes(Class,Frequency))+geom_bar(stat='identity',fill="green")
Output
Advertisements