R-在ggplot调用中获取一个变量的值以获得另一个变量的最大值

R - get value of one variable for maximum value of another variable INSIDE a ggplot call

我有一些这样的代码:

seq(0, 2*pi, length.out = 100) %>% 
  cbind.data.frame(t = ., Y = sin(.)) %>% 
  qplot(t, Y, data = ., geom = "line")+
  geom_segment(aes(y = mean(Y), yend = max(Y), x = , xend = ))

我想创建一个 geom_segment,其中参数 xxendt 的值,其中 Y 最高。我找到了 the question that describes how to find the value of one variable based on the maximum value of the other variable,但是,我不知道如何应用该解决方案以便它可以在 ggplot 调用中使用,而无需将对象保存到环境中。如有任何帮助,我们将不胜感激。

我不确定,因为输出很奇怪但是试试这个:

seq(0, 2*pi, length.out = 100) %>% 
  cbind.data.frame(t = ., Y = sin(.)) %>% 
  qplot(t, Y, data = ., geom = "line")+
  geom_segment(aes(y = mean(Y), 
                   yend = which(Y == max(Y)), 
                   x =  which(Y == max(Y)) , 
                   xend = which(Y == max(Y))))

使用 which.max,就像问题链接中的 post 一样,找到 Y 的第一个最大值并提取相应的 t 值。我还添加了水平轴。

suppressPackageStartupMessages({
  library(ggplot2)
  library(dplyr)
})

seq(0, 2*pi, length.out = 100) %>% 
  data.frame(t = ., Y = sin(.)) %>% 
  ggplot(aes(t, Y)) +
  geom_line() +
  geom_segment(aes(y = mean(Y), yend = max(Y), 
                   x = t[which.max(Y)], xend = t[which.max(Y)])) +
  geom_hline(yintercept = 0)

reprex package (v2.0.1)

于 2022-05-07 创建

或者(重新)计算 aesthetics“实时”,您可以对 geom 的数据框执行相同的操作。根据数据操作的程度,这在某些情况下很方便:

seq(0, 2*pi, length.out = 100) %>% 
  cbind.data.frame(t = ., Y = sin(.)) %>% 
  qplot(t, Y, data = ., geom = "line")+
  geom_segment(data = . %>%
                   mutate(mean_Y = mean(Y)) %>%
                   arrange(Y) %>% ## sort, so that row w highest Y comes last
                   tail(1), ## keep last row (with highest Y)
               aes(y = mean_Y, yend = Y,
                   x = t, xend = t)
)