draw geom_vlines with different colors relative to the modalities of a variable

172 views Asked by At

I have several geom_vline() in my plot coresponding to the date where the variable "cas" changes value and I want them to have a different colors relatively to the variable "cas". Is there a way to do that?

Here's my codes:

 df <- data.frame(date=c("2020-01-01 00:00:00","2020-01-01 03:00:00","2020-01-01 06:00:00","2020-01-01 09:00:00","2020-01-01 12:00:00","2020-01-01 15:00:00","2020-01-01 18:00:00",
            "2020-01-01 21:00:00","2020-01-02 00:00:00","2020-01-02 03:00:00"), cas=c("cas 0", "cas 0", "cas 0", "cas 1", "cas 1", "cas 1", "cas 2", "cas 2", "cas 2", "cas 0"), 
           meteo=c("t", "t", "t_S1", "P_S1","t_S1","P_S1","t", "t_S1", "t_S1", "P_S1"), valeur = c(-2.364850,-2.274782,-2.229748,-2.034601,-1.704351,-1.644305,-1.584260,-1.554237,-1.479181,-1.509203))

date_cas <- df[which(df$cas != dplyr::lag(df$cas)),] %>% select(date) %>% unlist()

date_cas <- date_cas %>% lubridate::parse_date_time2(., "YmdHMS") %>% format(.,"%Y-%m-%d %H:%M:%S" )

ggplot(df, aes(x=lubridate::date(date), y =valeur,colour=meteo, group = meteo )) +
  geom_line(size=0.8)+
  geom_vline( aes ( xintercept = lubridate::date(df$date[which(df$date %in% date_cas), colour = df$cas[which((df$date) %in% date_cas)] ])  , size=1, linetype = "dashed")+
  labs(y="", x = "Date")+
  theme_minimal()

I get this error : Erreur : Aesthetics must be either length 1 or the same as the data (10): xintercept and colour

can anyone help please ?

1

There are 1 answers

0
Ben On BEST ANSWER

I think a couple of parentheses/brackets needed to be moved, and would recommend subsetting df in geom_vline with data = df[df$date %in% date_cas, ].... This would help simplify your code a bit. See if this gives you what you need.

library(lubridate)
library(ggplot2)

df$date <- lubridate::date(df$date)

ggplot(df, aes(x=date, y=valeur, colour=meteo, group=meteo)) +
  geom_line(size=0.8)+
  geom_vline(data = df[df$date %in% date_cas, ],
             aes(xintercept=date, colour=cas),
             size=1, 
             linetype = "dashed")+
  labs(y="", x = "Date")+
  theme_minimal()