gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 12:40:02 24 4
gpt4 key购买 nike

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

怎么样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()

enter image description here

更新:

这个问题的解决方案已经出现在 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

关于r - ggplot2 密度与密度函数有何不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36781806/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com