为什么geom_density和stat_density(geom =“line”)给出不同的结果?

时间:2017-03-07 16:06:24

标签: r ggplot2

在下图中,为什么geom_densitystat_density(geom = "line")会给出不同的结果?

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

1 个答案:

答案 0 :(得分:8)

这是position参数的不同之处。 stat_density中的默认值为position = "stack",而geom_density()的默认值为position = "identity"

如果您致电p + stat_density(geom = "line", position = "identity"),则会与geom_density()

相同

enter image description here