Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a stacked density graph in ggplot2

Tags:

r

ggplot2

I'm trying to create a stacked density graph in ggplot2, and I am also trying to understand how qplot works relative to ggplot.

I found the following example online:

qplot(depth, ..density.., data=diamonds, geom="density", 
  fill=cut, position="stack")

I tried translating this into a call to ggplot because I want to understand how it works:

ggplot(diamonds, aes(x=depth, y=..density..)) + 
  geom_density(aes(fill=cut, position="stack"))

This creates a density graph, but does not stack it.

What is the different between what qplot is creating and what ggplot is creating?

Here is a stacked density graph:

stacked density

Non-stacked density graph:

enter image description here

Original example is here

like image 885
oneself Avatar asked Oct 19 '12 18:10

oneself


People also ask

What is a ggplot2 density plot?

A density plot is a representation of the distribution of a numeric variable. Comparing the distribution of several variables with density charts is possible. Here are a few examples with their ggplot2 implementation. A multi density chart is a density chart where several groups are represented.

How to create a density plot in R?

This R tutorial describes how to create a density plot using R software and ggplot2 package. The function geom_density () is used. You can also add a line for the mean using the function geom_vline.

What is the difference between a density plot and multi density chart?

A density plot is a representation of the distribution of a numeric variable. Comparing the distribution of several variables with density charts is possible. Here are a few examples with their ggplot2 implementation. A multi density chart is a density chart where several groups are represented. It allows to compare their distribution.

How to create a stacked bar plot for multiple variables?

The bar plot will display the stacked sum for each group of the variable. Setting stat = "identity" you can create a stacked bar plot for multiple variables. In this scenario you can pass other variable to aes, representing the value or count of that variable.


1 Answers

From @kohske's comment, the position is not an aesthetic, and so should not be inside the aes call:

ggplot(diamonds, aes(x=depth, y=..density..)) + 
  geom_density(aes(fill=cut), position="stack")

enter image description here

or using the movies data (which your example graphs use):

ggplot(movies, aes(x=rating, y=..density..)) + 
  geom_density(aes(fill=mpaa), position="stack")

enter image description here

like image 98
Brian Diggs Avatar answered Sep 29 '22 01:09

Brian Diggs