Home > OS >  Is it possible to conditionally format the color of a line without skipping points in between the &q
Is it possible to conditionally format the color of a line without skipping points in between the &q

Time:09-17

Sorry for the awkward title, but this is a weird little issue and I'm not sure how to better describe it.

Basically, I want to conditionally color a line in a time plot so that it's red when a condition is met and gray when it's not.

However, sometimes there are condition == FALSE values in between the condition == TRUE points, which causes the red line to jump over the condition == FALSE values (example below).

Note in the example that the red line at time == 6 jumps to time == 16, bypassing the three intermittent points.

I have tried setting the NA values to 0, but that doesn't seem to help.

Anyone have any suggestions?

df_plot <- tibble(
  id = rep(1, times = 10),
  time = seq(from = 0, to = 25, length.out = 10), 
  y_val = c(seq(from = 50, to = 25, length.out = 5),
            seq(from = 25, to = 50, length.out = 5)),
  con_val = c(NA, NA, 1, NA, NA, NA, 5, NA, NA, 2))
  
ggplot(data = df_plot, aes(x = time, y = y_val, color = con_val > 0))  
  geom_point()  
  geom_line()  
  scale_colour_manual(values = setNames(c('red','gray'), c(T, F))) 

An example of what I do not want.

CodePudding user response:

You need to define a a single group, because without one ggplot2 uses color as a group by default

ggplot(data = df_plot, aes(x = time, y = y_val, color = con_val > 0, group = 1))  
  geom_point()  
  geom_line()  
  scale_colour_manual(values = setNames(c('red','gray'), c(T, F)))

enter image description here

  • Related