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

Time:05-07

I have some code like this:

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

I want to create a geom_segment where the arguments x and xend take on the value of t for which Y is highest. I found the question that describes how to find the value of one variable based on the maximum value of the other variable, however, I don't know how to apply that solution so that it can be used within a ggplot call, without saving the object to the environemnt. Any help would be appreciated, thanks.

CodePudding user response:

Use which.max, like in the post the question links to, to find the first maximum of Y and extract the corresponding t value. I have also added the horizontal axis.

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)

Created on 2022-05-07 by the reprex package (v2.0.1)

CodePudding user response:

I am not sure, because the output is strange but try this:

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

CodePudding user response:

Alternatively to (re)calculating the aesthetics "live" you can do the same with the geom's dataframe. Depending on the extent of data manipulations, this is handy in some situations:

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

  • Related