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