If I understand your goal correctly, I think you can achieve it by creating two additional variables, say Season
and Color
that correspond to Date
column, and then supply the columns as necessary to geom_line
.
To make the steps and the results clearer, I create a dummy data by expanding your data to another year (2017) with similar date and category but slightly different values:
1. The data
df<-data.frame(Category= c("a","b","a","b"), Value = c(25,90,40,10), Date= c("2016-02-13", "2016-05-13", "2016-08-13", "2016-11-13"))
df2<-data.frame(Category= c("a","b","a","b"), Value = c(30,95,45,15), Date= c("2017-02-13", "2017-05-13", "2017-08-13", "2017-11-13"))
dat <- rbind.data.frame(df,df2)
dat
Category Value Date
1 a 25 2016-02-13
2 b 90 2016-05-13
3 a 40 2016-08-13
4 b 10 2016-11-13
5 a 30 2017-02-13
6 b 95 2017-05-13
7 a 45 2017-08-13
8 b 15 2017-11-13
2. Creating Season
and Color
columns
dat.season <- dat %>%
mutate(Date = as.Date(Date)) %>%
mutate(Month = months(Date)) %>%
mutate(Season = case_when(Month %in% c("March", "April", "May") ~ "spring",
Month %in% c("June", "July", "August") ~ "summer",
Month %in% c("September", "October", "November") ~ "autumn",
Month %in% c("December", "January", "February")~ "winter")) %>%
mutate(Color = case_when(Season == "spring"~ "yellow",
Season == "summer"~ "red",
Season == "autumn"~ "blue",
Season == "winter"~ "grey"))
dat.season
Category Value Date Month Season Color
1 a 25 2016-02-13 February winter grey
2 b 90 2016-05-13 May spring yellow
3 a 40 2016-08-13 August summer red
4 b 10 2016-11-13 November autumn blue
5 a 30 2017-02-13 February winter grey
6 b 95 2017-05-13 May spring yellow
7 a 45 2017-08-13 August summer red
8 b 15 2017-11-13 November autumn blue
Supplying the columns to geom_line()
dat.season %>% ggplot() +
geom_line(aes(x = Date, y = Value),
colour = dat.season$Color) +
theme_bw()
The result

Update to add coloured background
Here is the line plot along with coloured backgrounds for each season.
dat.season %>%
ggplot() +
geom_rect(aes(xmin = Date[1], xmax = Date[2],
ymin = Value[1], ymax = Value[2]),
fill = dat.season$Color[1])+
geom_rect(aes(xmin = Date[2], xmax = Date[3],
ymin = Value[2], ymax = Value[3]),
fill = dat.season$Color[2])+
geom_rect(aes(xmin = Date[3], xmax = Date[4],
ymin = Value[3], ymax = Value[4]),
fill = dat.season$Color[3])+
geom_rect(aes(xmin = Date[4], xmax = Date[5],
ymin = Value[4], ymax = Value[5]),
fill = dat.season$Color[4])+
geom_rect(aes(xmin = Date[5], xmax = Date[6],
ymin = Value[5], ymax = Value[6]),
fill = dat.season$Color[5])+
geom_rect(aes(xmin = Date[6], xmax = Date[7],
ymin = Value[6], ymax = Value[7]),
fill = dat.season$Color[6])+
geom_rect(aes(xmin = Date[7], xmax = Date[8],
ymin = Value[7], ymax = Value[8]),
fill = dat.season$Color[7])+
geom_line(aes(x = Date, y = Value)) +
theme_bw()
The result
