r - ggplot2中的geom_density和base R中的density的区别

标签 r ggplot2 kernel-density density-plot

我在 R 中有如下数据:

  bag_id location_type            event_ts
2     155        sorter 2012-01-02 17:06:05
3     305       arrival 2012-01-01 07:20:16
1     155      transfer 2012-01-02 15:57:54
4     692       arrival 2012-03-29 09:47:52
10    748      transfer 2012-01-08 17:26:02
11    748        sorter 2012-01-08 17:30:02
12    993       arrival 2012-01-23 08:58:54
13   1019       arrival 2012-01-09 07:17:02
14   1019        sorter 2012-01-09 07:33:15
15   1154      transfer 2012-01-12 21:07:50

其中 class(event_ts) 是 POSIXct

我想找出不同时间每个地点的行李密度。

我使用了命令 geom_density(ggplot2) 并且我可以很好地绘制它。我想知道 density(base) 和这个命令之间是否有任何区别。我的意思是他们使用的方法或他们使用的默认带宽等方面的任何差异。

我需要将密度添加到我的数据框中。如果我使用函数 density(base),我知道如何使用函数 approxfun 将这些值添加到我的数据框中,但我想知道它是否是当我使用 geom_density(ggplot2) 时也是如此。

最佳答案

快速浏览 ggplot2 documentation for geom_density()表明它包含了 stat_density() 中的功能。那里的第一个参数引用来自基本函数 density()adjust 参数。因此,对于您的直接问题 - 它们是基于相同的功能构建的,尽管使用的确切参数可能不同。您可以对设置这些参数进行一些控制,但您可能无法获得所需的灵 active 。

使用 geom_density() 的一种替代方法是在 ggplot() 之外计算您想要的密度,然后使用 geom_line()。例如:

library(ggplot2)
#100 random variables
x <- data.frame(x = rnorm(100))
#Calculate own density, set parameters as you desire
d <- density(x$x)
x2 <- data.frame(x = d$x, y = d$y)

#Using geom_density()
ggplot(x, aes(x)) + geom_density()
#Using home grown density
ggplot(x2, aes(x,y)) + geom_line(colour = "red")

在这里,它们给出了几乎相同的图,尽管它们可能会因您的数据和设置而有更大的差异。

关于r - ggplot2中的geom_density和base R中的density的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18162425/

相关文章:

r - R中的高效随机抽样

R:如何将 data.frame 拆分为具有 2 列的更小的 data.frame

r - 有没有办法在ggplot中将x轴设置为最小值和最大值?

r - 使用 ggplot2 和 geom_text 在比例条形图中插入标签

r - R 中的二次判别分析 (QDA) 图

python - 如何比较R中两个向量的分布?

r - R中数据帧的并行处理

RMarkdown Reveal.js 演示代码折叠

python - 如何在 Tensorflow 中执行核密度估计

r - 为什么我对球体的核密度估计不起作用?