What is the best way to calculate and display peaks of a ggplot2::geom_density() object?

落爺英雄遲暮 提交于 2020-01-02 10:09:05

问题


I'm trying to find an easy and intuitive way to calculate and display the peaks of a ggplot2::geom_density() object.

This blog explains how to do it in base R, but it is a multistep process.

But it seems much more intuitive to use the stat_peaks() function of the ggpmisc package.

However, when running the code below, I get the error: stat_peaks requires the following missing aesthetics: y

library(tidyverse)
library(ggpmisc)

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

When creating a geom_density() you don't need to supply a y aesthetic.

So if indeed stat_peaks is the way to go, is there a work around to this issue? Perhaps there is a better solution to my problem.


回答1:


Here is a simple workaround. The idea is to call ggplot_build, let ggplot do the calculations for you and then extract the needed y aesthetic from the resulting object, which is density in your case.

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
)

I'm sure that this approach can be improved by one of the ggplot2 wizards around that can explain why this is not working...

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

error: stat_peaks requires the following missing aesthetics: y

... which was my first guess.



来源:https://stackoverflow.com/questions/53841391/what-is-the-best-way-to-calculate-and-display-peaks-of-a-ggplot2geom-density

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!