- 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 stacked plot with density using ggplot2 in R?
To create stacked plot with density using ggplot2, we can use geom_density function of ggplot2 package and position="stack". For example, if we have a data frame called df that contains two columns say x and y, where x is categorical and y is numerical then the stacked plot with density can be created by using the command −
ggplot(df,aes(y,y=..density..))+geom_density(aes(fill=x),position="stack")
Example
Consider the below data frame −
> x<-sample(LETTERS[1:4],20,replace=TRUE) > y<-rpois(20,5) > df<-data.frame(x,y) > df
Output
x y 1 C 3 2 C 5 3 B 4 4 A 7 5 B 1 6 A 6 7 D 4 8 C 3 9 C 7 10 B 4 11 D 3 12 C 9 13 A 4 14 A 3 15 B 4 16 B 8 17 A 7 18 C 5 19 D 4 20 B 5
Loading ggplot2 package and creating stacked plot with density of y −
> library(ggplot2) > ggplot(df,aes(y,y=..density..))+geom_density(aes(fill=x),position="stack")
Output
- Related Articles
- How to create a stacked bar plot with vertical bars in R using ggplot2?
- How to create the stacked bar plot using ggplot2 in R with labels on the plot?
- How to create a bar plot with ggplot2 using stat_summary in R?
- How to create bar plot with log values using ggplot2 in R?
- Create stacked bar chart with percentages on Y-axis using ggplot2 in R.
- How to create a dot plot using ggplot2 in R?
- How to create an empty plot using ggplot2 in R?
- How to create transparent bar plot using ggplot2 in R?
- How to create a plot title with unicode characters using ggplot2 in R?
- How to create bar plot with gradient colors using ggplot2 in R?\n
- How to create facetted plot with facets in horizontal direction using ggplot2 in R?
- How to create density plot for categories in R?
- How to create a bar plot using ggplot2 with percentage on Y-axis in R?
- How to create violin plot for categories with grey color palette using ggplot2 in R?
- How to create facetted plot with one facet displaying all data using ggplot2 in R?

Advertisements