计算和显示ggplot2 :: geom_density()对象的峰的最佳方法是什么? [英] What is the best way to calculate and display peaks of a ggplot2::geom_density() object?

查看:445
本文介绍了计算和显示ggplot2 :: geom_density()对象的峰的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试找到一种简单直观的方法来计算和显示ggplot2 :: geom_density()对象的峰.

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

此博客解释了如何在基本R中做到这一点.多步骤过程.

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

但是使用 ggpmisc 包.

但是,在运行下面的代码时,出现错误:stat_peaks requires the following missing aesthetics: y

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

在创建geom_density()时,您无需提供y的美感.

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

因此,如果确实要使用stat_peaks,是否可以解决此问题?也许对我的问题有更好的解决方案.

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.

推荐答案

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

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
)

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

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()

错误:stat_peaks需要以下美感:y

error: stat_peaks requires the following missing aesthetics: y

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

... which was my first guess.

这篇关于计算和显示ggplot2 :: geom_density()对象的峰的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆