- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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 create density plot for categories filled with different colors in R?
To create density plot for categories filled with different colors, we can follow the below steps −
- Frist of all, create a data frame.
- Load ggplot2 package and creating the density plot for the categories.
- Create the density plot for the categories in the data frame by using fill function.
Create the data frame
Let's create a data frame as shown below −
x<-sample(LETTERS[1:3],20,replace=TRUE) y<-sample(1:100,20) df<-data.frame(x,y) df
On executing, the above script generates the below output(this output will vary on your system due to randomization) −
x y 1 C 19 2 A 49 3 A 94 4 C 5 5 A 45 6 A 23 7 B 33 8 A 99 9 C 73 10 A 1 11 B 84 12 A 61 13 A 7 14 C 51 15 B 43 16 B 31 17 C 67 18 C 77 19 C 50 20 B 80
Creating density plot for categories
Use geom_density with col function to create the density plot for categories −
library(ggplot2) x<-sample(LETTERS[1:3],20,replace=TRUE) y<-sample(1:100,20) df<-data.frame(x,y) ggplot(df,aes(y))+geom_density(aes(col=x),alpha=0.2)
Output
Create the density plot for the categories filled with different colors
Use geom_density with fill function to create the density plot for categories filled with different colors −
x<-sample(LETTERS[1:3],20,replace=TRUE) y<-sample(1:100,20) df<-data.frame(x,y) ggplot(df,aes(y))+geom_density(aes(fill=x),alpha=0.2)
Output
- Related Articles
- How to create density plot for categories in R?
- How to manually set the colors of density plot for categories in R?
- How to create violin plot for categories with grey color palette using ggplot2 in R?
- How to create stacked plot with density using ggplot2 in R?
- How to create bar plot with gradient colors using ggplot2 in R?
- How to create a plot using rgb colors in R?
- How to create violin plot for categories with grey color palette in reverse order using ggplot2 in R?
- How to create bar plot in base R with different limits for Y-axis?
- How to create horizontal lines with two different colors after a threshold in R?
- How to create plot in R with different shape of points?
- Plot different colors for different categorical levels using matplotlib
- How to create boxplot for multiple categories with long names in base R?
- How to create a bar plot in R filled with color palette in RColorBrewer package?
- How to create a plot in R with a different plot window size using plot function?
- How to create boxplot for multiple categories in base R?

Advertisements