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

In the following figure, why geom_densityand 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()

geometry results_

p + stat_density(geom = "line")

stat_density results

+4
source share
1 answer

This is the difference in argument position. The default stat_densityvalue is position = "stack", and with geom_density()- position = "identity".

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

enter image description here

+7
source

Source: https://habr.com/ru/post/1671721/


All Articles