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

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 ?

You cannot map an aesthetic element to an external vector, if you want to pass a vector you have to do it outside the aes() function, for example:

library(ggplot2)

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 <- c("2020-01-01 09:00:00", "2020-01-01 18:00:00", "2020-01-02 03:00:00")

ggplot(df, aes(x=as.Date(date), y = valeur, colour = meteo, group = meteo)) +
    geom_line(size=0.8) +
    geom_vline(xintercept = as.Date(date_cas),
               colour = c("blue", "red", "green"),
               size = 1,
               linetype = "dashed") +
    labs(y = "", x = "Date") +
    theme_minimal()

Created on 2020-12-02 by the reprex package (v0.3.0.9001)

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.