Create a stacked density graph in ggplot2

2019-06-19 19:17发布

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

标签: r ggplot2
1条回答
虎瘦雄心在
2楼-- · 2019-06-19 19:33

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

查看更多
登录 后发表回答