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

标签 r ggplot2 density-plot

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

怎么样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/

相关文章:

r - 在 R 中使用 ssh 隧道连接到数据库 PostgreSQL

R/ggplot2/geom_密度 : how to use values in cells rather than number of entries

r - 如何计算 R 中函数 hist() 结果的密度

r - ggplot2中密度曲线下的阴影面积

r - 如何在 R 中进行分类时间序列预测?

r - 如何计算第一个和最后一个分数之间的差异

R ggplot2 : annotation_custom of raster grob does not plot

r - 如何扩展我的 R Shiny 应用程序以获得更大的数据输入?

r - ggplot2图形缓存与knitr

python - 如何制作大型二维散点图的等高线/密度图