ggplot2的密度图和密度函数有何不同?

8
以下两个图形为何看起来不同?两种方法都使用高斯核。 ggplot2 如何计算密度?
library(fueleconomy)

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

enter image description here

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

在这里输入图片描述


更新:

此问题的解决方案已经在SO上出现,在这里,然而ggplot2传递给R stats density函数的具体参数仍不清楚。

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


感谢提供参考。然而,该解决方案似乎无法识别显式参数差异。我想知道如何从ggplot密度图中生成/提取精确的密度数据。 - Megatron
1
这似乎是提取geom_density图的确切值的算法:https://dev59.com/P2ct5IYBdhLWcg3wCZMT - fanli
我认为这与密度无关,而是与您如何应用对数变换有关。 - user20650
1
尝试 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() - user20650
考虑切换到 ggalt::geom_bkde() 以获得更好的密度估计。 - hrbrmstr
显示剩余2条评论
1个回答

3
在这种情况下,不同的是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中,似乎在密度计算之前将对x变量进行了log10变换。因此,要手动重新产生结果,必须在计算密度之前对变量进行转换。例如:

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()

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接