ggplot2 密度与密度函数有何不同?

How does ggplot2 density differ from the density function?

为什么下面的图看起来不一样?这两种方法似乎都使用高斯内核。

ggplot2如何计算密度?

library(fueleconomy)

d <- density(vehicles$cty, n=2000)
ggplot(NULL, aes(x=d$x, y=d$y)) + geom_line() + scale_x_log10()

ggplot(vehicles, aes(x=cty)) + geom_density() + scale_x_log10()


更新:

这个问题的解决方案已经出现在 SO here 上,但是 ggplot2 传递给 R 统计密度函数的具体参数仍然不清楚。

另一种解决方案是直接从 ggplot2 图中提取密度数据,如图 here

在这种情况下,不同的不是密度计算,而是如何 应用 log10 变换。

首先检查没有变换的密度是否相似

library(ggplot2)
library(fueleconomy)

d <- density(vehicles$cty, from=min(vehicles$cty), to=max(vehicles$cty))
ggplot(data.frame(x=d$x, y=d$y), aes(x=x, y=y)) + geom_line() 
ggplot(vehicles, aes(x=cty)) + stat_density(geom="line")

所以问题似乎出在变换上。在下面的 stat_density 中,它似乎是 如果在密度计算之前将 log10 变换应用于 x 变量。 因此,要手动重现结果,您必须先转换变量 计算密度。例如

d2 <- density(log10(vehicles$cty), from=min(log10(vehicles$cty)), 
                                               to=max(log10(vehicles$cty)))
ggplot(data.frame(x=d2$x, y=d2$y), aes(x=x, y=y)) + geom_line() 
ggplot(vehicles, aes(x=cty)) + stat_density(geom="line") + scale_x_log10()

PS:要了解ggplot如何为密度准备数据,可以查看代码as.list(StatDensity)导致StatDensity$compute_groupggplot2:::compute_density