- 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 fill bars of a bar plot created using ggplot2 with colors based on frequency?
To fill bars in a bar plot using ggplot2 in R with colors based on frequency, we can use fill argument with count.
For Example, if we have a data frame called df that contains a single column X that contains repeated values and we want to create bar plot of values in X based on their frequencies then we can use the below command −
ggplot(df)+geom_bar(aes(X,fill=..count..))
Example
Consider the data frame given below −
x<-rpois(20,2) df<-data.frame(x) df
The following dataframe is created
x 1 1 2 2 3 2 4 3 5 1 6 0 7 3 8 3 9 3 10 2 11 1 12 1 13 1 14 2 15 1 16 1 17 0 18 2 19 4 20 1
To load the ggplot2 package and create bar chart filled with colors based on frequency of values in x on the above created data frame, add the following code to the above snippet −
x<-rpois(20,2) df<-data.frame(x) library(ggplot2) ggplot(df)+geom_bar(aes(x,fill=..count..))
Output
If you execute all the above given snippets as a single program, it generates the following Output −
- Related Articles
- Fill bars in a base R barplot with colors based on frequency.
- How to fill histogram bars using ggplot2 in R with different colors?
- How to create a bar plot in R with label of bars on top of the bars using ggplot2?
- Why scale_fill_manual does not fill the bar with colors created by using ggplot2 in R?
- How to create a stacked bar plot with vertical bars in R using ggplot2?
- How to create bar plot with gradient colors using ggplot2 in R?\n
- How to change the thickness of the borders of bars in bar plot created by using ggplot2 in R?
- How to reverse the bars of a bar plot a using ggplot2 in R?
- How to change the color of bars of a bar plot using ggplot2 in R?
- How to increase the space between bars of a bar plot using ggplot2 in R?
- How to create bar plot of means with error bars of standard deviations using ggplot2 in R?
- How to change the bars color to grey shade of a bar graph created by using ggplot2 in R?
- How to change legend values in a bar plot created by using ggplot2 in R?
- How to align the text horizontally in a bar plot created by using ggplot2 in R?
- How to create the stacked bar plot using ggplot2 in R with labels on the plot?

Advertisements