1

is there a function that enables me to highlight i.e. a y max value on a geom smooth plot?

I have tried with ggHighlight but I can not get it to work on this problem.

Christian
  • 35
  • 2
  • It would be easier for the community to help you, if you provide a reproducible example with expected output. So everyone can test their ideas and see which one might be an answer. Here are some information about reproducible examples: https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – tamtam Mar 04 '21 at 09:28

1 Answers1

0

You can get the layer data to get the values that ggplot computed and filter for the extrema.

library(ggplot2)

# Generate some dummy data
x <- seq(0, 2 * pi, length.out = 100)
df <- data.frame(
  x = x,
  y = sin(x) + rnorm(length(x), sd = 0.2)
)

# Make plot
g <- ggplot(df, aes(x, y)) +
  geom_smooth()

# Get and filter extrema
ld <- layer_data(g)
#> `geom_smooth()` using method = 'loess' and formula 'y ~ x'
ld <- ld[c(which.max(ld$y), which.min(ld$y)), ]

# Make an annotation
g + geom_segment(
  data = ld,
  aes(x = x, y = y, xend = x, yend = c(Inf, -Inf)),
  arrow = arrow(ends = "first")
)
#> `geom_smooth()` using method = 'loess' and formula 'y ~ x'

teunbrand
  • 33,645
  • 4
  • 37
  • 63