So I'm working with a graph that I would like to add maxima/minima lines to. I've checked out this and this which have provided me really useful information, but I'm not able to decipher from these posts how to do exactly what I want to my graphs.
I have a function that that shows peaks and valleys of specific types of water balance variables through a year. I want to show a shifting in the peaks and valleys of these variables as we get closer to 2100. Using the code from the first page I linked
gb <- ggplot_build(.y_plot_bc)
exact_x_value_of_the_curve_maximum <- gb$data[[1]]$x[which(diff(sign(diff(gb$data[[1]]$y)))==-2)+1]
.y_plot_bc <- .y_plot_bc + geom_vline(xintercept=exact_x_value_of_the_curve_maximum)
I was able to find the local maxima of the stat_smooth function in my code, but unfortunately, it is giving me way too many lines. I only want the HIGHEST maxima on the graph, not ALL maxima. Additionally, I have one graph from my function that needs the minima. I assume I can code an ifelse()
for that, but am curious if there is a less clunky way of doing it. Finally, I would like the maxima/minima to be the same colors as the lines they are running through. Any tips or tricks for any of these problems would be greatly appreciated. The biggest problem for me is only getting geom_vline
to go through the highest peaks on the graph, because that's some advanced coding/mathematics that I don't know how to tackle.
Here is a reproducible example (please let me know if it isn't! I'm still new to stack):
library(RCurl)
library(tidyverse)
library(splines)
doy_avg_bc_test <- read_csv("https://raw.githubusercontent.com/Janelle88/water_balance/95bd248d6be22a8619026d5c43f2bc462aa09c8e/doy_avg_bc")
plot_decades_smooth = function(.y) {
.y_plot_bc <- ggplot(doy_avg_bc_test) +
stat_smooth(size = 1.5,
se = FALSE,
aes(x = doy,
y = .data[[.y]],
group = decades,
color = decades),
method = glm,
family = quasipoisson,
formula = y ~ ns(x, 16)) +
scale_color_manual(breaks = c("1980-2019", "2020-2059", "2060-2099"),
values = c("#A3B86C", "#EBC944", "#1496BB"))
gb <- ggplot_build(.y_plot_bc)
exact_x_value_of_the_curve_maximum <- gb$data[[1]]$x[which(diff(sign(diff(gb$data[[1]]$y)))==-2)+1]
.y_plot_bc <- .y_plot_bc + geom_vline(xintercept=exact_x_value_of_the_curve_maximum)
print(.y_plot_bc)
}
plot_decades_smooth("runoff_daily")
plot_decades_smooth("soil_water_daily")
This graph is an example of the graph that I would like only the highest peaks to have the maxima for. This graph is and example of the graph that I would like the minima for.