Suppose I have a linegraph with n lines. Each line has a corresponding x-axis value for which I want a different color before and after a specific event.
For example, each person starts as the color green, but when they have an event, the line color switches to red.
I was able to find a solution in base using loops, looking for a base or ggplot solution.
CodePudding user response:
lines <- data.frame(id = rep(c("A","B"), each = 5),
x = 1:5,
val = 1:10)
events <-data.frame(id = c("A","B"),
time = c(3, 4))
library(tidyverse)
lines %>%
left_join(events) %>%
group_by(id) %>%
mutate(status = if_else(x < time, "before", "after")) %>%
ggplot(aes(x, val, color = status, group = id))
geom_line(size = 4)