【问题标题】:What is the best way to calculate and display peaks of a ggplot2::geom_density() object?计算和显示 ggplot2::geom_density() 对象的峰值的最佳方法是什么?
【发布时间】:2019-05-19 08:45:02
【问题描述】:

我试图找到一种简单直观的方法来计算和显示 ggplot2::geom_density() 对象的峰值。

This blog 解释了如何在基础 R 中执行此操作,但这是一个多步骤的过程。

但使用 ggpmisc 包的 stat_peaks() 函数似乎更直观。

但是,当运行下面的代码时,我得到了错误:stat_peaks requires the following missing aesthetics: y

library(tidyverse)
library(ggpmisc)

ggplot(iris, aes(x = Petal.Length)) +
  geom_density() +
  stat_peaks(colour = "red")

创建 geom_density() 时,您不需要提供 y 美学。

所以如果确实 stat_peaks 是要走的路,有没有办法解决这个问题?也许对我的问题有更好的解决方案。

【问题讨论】:

    标签: r ggplot2 tidyverse ggpmisc


    【解决方案1】:

    这是一个简单的解决方法。想法是调用ggplot_build,让ggplot 为您进行计算,然后从结果对象中提取所需的y 美学,在您的情况下为density

    library(ggplot2)
    library(ggpmisc)
    
    p <- ggplot(iris, aes(x = Petal.Length)) +
      geom_density()
    
    pb <- ggplot_build(p)
    p + stat_peaks(
      data = pb[['data']][[1]], # take a look at this object
      aes(x = x, y = density),
      colour = "red",
      size = 3
    )
    

    我确信这种方法可以通过一个 ggplot2 向导来改进,它可以解释为什么这不起作用......

    ggplot(iris, aes(x = Petal.Length, y = stat(density))) +
      geom_density() +
      stat_peaks()
    

    错误:stat_peaks 需要以下缺失的美学:y

    ...这是我的第一个猜测。

    【讨论】:

    • 不知道为什么你投了反对票.....另外:提取与红点对应的值的最佳方法是什么?
    • 要获取值,请尝试head(sort(pb[['data']][[1]]$density, decreasing = TRUE), 2)。欲了解更多信息,请查看:ianmadd.github.io/pages/PeakDensityDistribution.html
    猜你喜欢
    • 1970-01-01
    • 2020-09-26
    • 2015-08-21
    • 2016-04-01
    • 2020-02-13
    • 1970-01-01
    • 2010-11-08
    • 2013-03-17
    • 1970-01-01
    相关资源
    最近更新 更多