我试图找到一种简单直观的方法来计算和显示 ggplot2::geom_densis() 对象的峰值。
这个博客 http://ianmadd.github.io/pages/PeakDensityDistribution.html解释了如何在基础 R 中执行此操作,但这是一个多步骤的过程。
但使用 stat_peaks() 函数似乎更直观ggpmisc https://docs.r4photobiology.info/ggpmisc/reference/stat_peaks.html包裹。
但是,当运行下面的代码时,我收到错误: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_密度() 时,您不需要提供 y 美学。
因此,如果 stat_peaks 确实是可行的方法,那么是否有解决此问题的方法?也许有更好的方法来解决我的问题。
这是一个简单的解决方法。这个想法是打电话ggplot_build
, let 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
...这是我的第一个猜测。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)