【问题标题】:The difference between geom_density in ggplot2 and density in base Rggplot2 中的 geom_density 和 base R 中的密度之间的差异
【发布时间】:2013-08-12 07:32:55
【问题描述】:

我在 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) 时是否相同。

【问题讨论】:

    标签: r ggplot2 kernel-density density-plot


    【解决方案1】:

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

    使用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")
    

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

    【讨论】:

    • 文档链接已损坏?
    • @Matifou - 更新链接....这在 2013 年得到了回答...R 宇宙在那个时候已经进化了一点。
    猜你喜欢
    • 1970-01-01
    • 2012-10-19
    • 1970-01-01
    • 2012-05-11
    • 1970-01-01
    • 1970-01-01
    • 2014-09-10
    • 2017-06-27
    • 2014-11-17
    相关资源
    最近更新 更多