Meg*_*ron 7 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()
Run Code Online (Sandbox Code Playgroud)
ggplot(vehicles, aes(x=cty)) + geom_density() + scale_x_log10()
Run Code Online (Sandbox Code Playgroud)
更新:
这个问题的解决方案已经在SO上出现了,但是ggplot2传递给R stats密度函数的具体参数仍然不清楚.
一种替代的解决方案是从GGPLOT2情节直提取密度数据,如图这里
在这种情况下,不同的不是密度计算,而是 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")
Run Code Online (Sandbox Code Playgroud)
所以问题似乎是转变。在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()
Run Code Online (Sandbox Code Playgroud)
PS:要了解如何ggplot准备密度数据,您可以查看as.list(StatDensity)代码StatDensity$compute_groupggplot2:::compute_density