I have want to create a line plot with a gradient colouring aesthetic if a certain value drops below a threshold:
library(tidyverse)
foo <- tribble(
~x, ~y, ~c
, 1, 1, 1
, 2, 2, 2
, 3, 3, 3
, 4, 4, 4
)
foo %>%
ggplot(aes(x, y, colour = c)) +
geom_line(size = 3) +
scale_colour_gradient2(low = "red", mid = "green", high = "green", midpoint = 3)
I want to create multiple of these plots with the same colouring logic, i.e. a gradient between green and red for 1 <= c <= 3. But when the underlying data changes, the colour gradient changes as well:
foo <- tribble(
~x, ~y, ~c
, 1, 1, 1
, 2, 2, 2
, 3, 3, 3
, 4, 4, 100
)
foo %>%
ggplot(aes(x, y, colour = c)) +
geom_line(size = 3) +
scale_colour_gradient2(low = "red", mid = "green", high = "green", midpoint = 3)
I hope someone has a better answer than recalculating the underlying variable (foo %>% mutate(c = ifelse(c > 4, 4, c))).


