ggplot2 密度与密度函数有何不同?
Posted
技术标签:
【中文标题】ggplot2 密度与密度函数有何不同?【英文标题】:How does ggplot2 density differ from the density function? 【发布时间】:2016-08-15 09:00:18 【问题描述】:为什么下面的图看起来不同?这两种方法似乎都使用高斯核。
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 stats 密度函数的具体参数仍不清楚。
另一种解决方案是直接从 ggplot2 图中提取密度数据,如图所示here
【问题讨论】:
感谢您的参考。但是,该解决方案似乎无法识别显式参数差异。我想知道如何从 ggplot 密度中生成/提取精确的密度数据。 这似乎提取了 geom_density 图的确切值:***.com/questions/12394321/… 我不认为这与密度有关,而是您如何应用日志转换 我可以应用替代日志转换来使它们相同吗? 例如尝试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()
:但您需要调整轴标签。 Ansggplot(vehicles, aes(x=cty)) + stat_density(geom="line") + scale_x_log10()
【参考方案1】:
在这种情况下,不同的不是密度计算,而是如何 应用 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_group
到ggplot2:::compute_density
【讨论】:
以上是关于ggplot2 密度与密度函数有何不同?的主要内容,如果未能解决你的问题,请参考以下文章
R语言ggplot2可视化绘制二维的密度图:在R中建立二维散点数据的连续密度热图2D密度估计MASS包中的kde2d函数实现2D密度估计geom_density2d函数可视化二维密度图
R语言使用ggplot2包的快速可视化函数qplot绘制基础密度图实战
R语言使用ggplot2包的快速可视化函数qplot绘制密度图(主题轴标签设置)实战