Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do geom_density and stat_density(geom = "line") give different results?

Tags:

r

ggplot2

In the following illustration, why do geom_density and stat_density(geom = "line") give different results?

library(ggplot2)

df <- data.frame(
  x.values = c(
    rnorm(100, mean = 1, sd = 1),
    rnorm(100, mean = 4, sd = 1),
    rnorm(100, mean = 7, sd = 1),
    rnorm(100, mean = 10, sd = 1)
  ),
  mean.values = sort(rep(c(1, 4, 7, 10), 100))
)

p <- ggplot(df, aes(x = x.values, color = mean.values, group = mean.values))

p + geom_density()

geom_density results

p + stat_density(geom = "line")

stat_density results

like image 713
Jake Fisher Avatar asked Mar 07 '17 16:03

Jake Fisher


Video Answer


1 Answers

It's a difference in the position argument. The default in stat_density is position = "stack", whilst with geom_density() it is position = "identity".

If you call p + stat_density(geom = "line", position = "identity") you get the same as geom_density():

enter image description here

like image 169
Gavin Simpson Avatar answered Oct 23 '22 06:10

Gavin Simpson