Search code examples
rggplot2positionvline

Display position of a y-maximum using ggplot


I used ggplot to create a plot:

pl <- ggplot(df, aes(x=xval, y=as.numeric(BS))) + 
    geom_point(shape=21) + 
    xlab("Threshold") + 
    ylab("BS") + 
    geom_vline(xintercept=df$xval[as.numeric(df$BS) == max(as.numeric(df$BS))],color='red') +
    geom_hline(yintercept=max(as.numeric(df$BS)),color='darkblue',linetype=2)

The red line tells me where the maximum of BS is.

Is there a way to display the x-position and y-position of this value?

It should be something like (for example): P(0.5, 0.8).


Solution

  • You can use geom_label() here after filtering your data. Here using the mtcars dataset as an example:

    ggplot(mtcars, aes(x = disp, y = qsec)) +
      geom_point(shape = 21) + 
      geom_vline(xintercept = mtcars$disp[as.numeric(mtcars$qsec) == max(as.numeric(mtcars$qsec))],color='red') +
      geom_hline(yintercept = max(as.numeric(mtcars$qsec)), color = 'darkblue', linetype = 2) +
      geom_label(data = . %>% filter(qsec == max(qsec)), 
                 aes(label = paste0("P(", disp, ", ", qsec, ")")), hjust = -0.5)
    

    enter image description here