【问题标题】:ggplot2: add line for average count values resulting from geom_freqpolyggplot2:为 geom_freqpoly 产生的平均计数值添加行
【发布时间】:2020-05-24 05:58:59
【问题描述】:

我正在尝试在我的 geom_freqpoly 图中添加一条额外的线,表示每个 binwidth 的平均计数。我尝试了两种不同的方法,但都没有成功。

  1. 我尝试将该行添加为 geom_line,但在询问我是否将我的统计信息映射到错误图层时出现错误。
library(tidyverse)

iris %>% 
  ggplot(aes(x = Petal.Length, y = ..count..)) +
  geom_freqpoly(aes(color = Species), 
                binwidth = 0.2) +
  geom_line(aes(yintercept = "mean"))
#> Warning: Ignoring unknown aesthetics: yintercept
#> Error: Aesthetics must be valid computed stats. Problematic aesthetic(s): y = ..count... 
#> Did you map your stat in the wrong layer?
  1. 我尝试添加另一个 geom_freqpoly,例如:
library(tidyverse)

iris %>% 
  ggplot() +
  geom_freqpoly(aes(x = Petal.Length, y = ..count.., color = Species), 
                binwidth = 0.2) +
  geom_freqpoly(aes(x = Petal.Length, y = mean(..count..), color = "red"), binwidth = 0.2)

但结果不是我所期望的。

使用 Iris 数据集,我希望新行将代表按定义的 binwidth 的平均物种计数(见下图),而不是我得到的。我的理解是 geom_freqpoly 将连续变量(如 Petal.Length)划分为长度箱(在这种情况下为 0.2 长度)。因此,对于每个箱,我希望获得每个物种的平均数量并绘制一条连接这些点的线。

reprex package (v0.3.0) 于 2020 年 5 月 23 日创建

【问题讨论】:

    标签: r ggplot2 statistics tidyverse frequency


    【解决方案1】:

    根据您对问题的编辑,这可能是您所期望的。

    你的方法的问题是mean(..count..) 只是计算向量..count.. 的平均值,它给你一个数字,因此是一条水平线。因此只需除以groupsSpecies 的数量

    我对我的解决方案并不完全满意,因为我想避免使用代码 n_distinct(iris$Species)。我用tapply 尝试了一些方法,但失败了。所以作为第一步......

    library(tidyverse)
    
    ggplot(iris, aes(x = Petal.Length)) +
      geom_freqpoly(aes(color = Species), binwidth = .2) +
      geom_freqpoly(aes(y = ..count.. / n_distinct(iris$Species)), color = "red", binwidth = .2)
    

    reprex package (v0.3.0) 于 2020 年 5 月 28 日创建

    【讨论】:

    • 非常感谢!!这就是我需要的。感谢您的解释,我很感激!
    猜你喜欢
    • 2016-04-21
    • 2011-05-13
    • 1970-01-01
    • 1970-01-01
    • 2020-12-04
    • 2020-08-10
    • 1970-01-01
    • 2015-01-13
    • 1970-01-01
    相关资源
    最近更新 更多