- 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 create density plot for categories in R?
To create density plot for categories, we can follow the below steps −
- Frist of all, create a data frame.
- Load ggplot2 package and creating the density plot for the whole data.
- Create the density plot for the categories in the data frame by using col 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 A 47 2 B 46 3 B 29 4 C 53 5 C 60 6 C 17 7 B 79 8 B 12 9 B 30 10 C 91 11 A 92 12 A 2 13 B 25 14 B 98 15 B 88 16 C 34 17 C 50 18 A 20 19 C 90 20 B 87
Loading ggplot2 package and creating a density plot for whole data
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()
Output
Create density plot based on categories
Use col function inside aes of geom_density function to create the density plot based on 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
- Related Articles
- How to create density plot for categories filled with different colors 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 boxplot for multiple categories in base R?
- How to create violin plot for categories with grey color palette in reverse order using ggplot2 in R?
- How to create boxplot for multiple categories with long names in base R?
- How to create a classification model using svm for multiple categories in R?
- How to create scatterplot for categories with grey color palette using ggplot2 in R?
- How to create boxplot for categories with grey color palette using ggplot2 in R?
- How to create line chart for categories with grey color palette using ggplot2 in R?
- How to create an ID column in R based on categories?
- How to create ACF plot in R?
- How to create a colored box for base R plot?
- How to create boxplot for categories with grey color palette in reverse order using ggplot2 in R?

Advertisements