2

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

s28
  • 173
  • 5

2 Answers2

2

Add a text annotation using the geom_text() function in ggplot:

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) +
  geom_text(
    x = df$xval[as.numeric(df$BS) == max(as.numeric(df$BS))],
    y = max(as.numeric(df$BS)),
    label = paste0("P(", round(df$xval[as.numeric(df$BS) == max(as.numeric(df$BS))], 2), ", ", round(max(as.numeric(df$BS)), 2), ")"),
    vjust = -1.5,
    color = "black"
  )

The paste0() function is used to concatenate the position information in the desired format (e.g., "P(0.5, 0.8)").

Adjust the vjust parameter as needed to fine-tune the vertical positioning of the text.

Daniel_Kamel
  • 610
  • 8
  • 29
2

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

jpsmith
  • 11,023
  • 5
  • 15
  • 36