ggplot a time series with multiple groups
Consider a simple time series:
tbl <- tibble::tibble(
Date = seq(from = as.Date("2020-01-01"), to = as.Date("2020-01-31"), by = 1),
Value = rnorm(31)
I want to plot this time series, but with weekdays and weekends having different colors.
First I add a column with the kind of day:
tbl_with_days <- tbl %>%
DayOfWeek = lubridate::wday(Date, week_start = 1),
DayType = ifelse(DayOfWeek <= 5, "Weekday", "Weekend")
Simply adding colors to a ggplot will not look correct, because ggplot connects points within the same group:
ggplot(aes(Date, Value, color = DayType)) +
Instead we can use a slightly different aesthetic in the
ggplot(aes(Date, Value, group = 1, color = DayType)) +
Since we are dealing with time series it is tempting to use the tsibble package.
First the tibble is converted to a tsibble.
tsbl_with_days <- tbl_with_days %>%
dplyr::select(Date, DayType, Value) %>%
tsibble::as_tsibble(key = DayType, index = Date)
key parameter specifies that we have two kinds of time series, namely for the kind of
Furthermore, for a regularly sampled time series, we can fill in the implicitly missing observations with
autoplot function from ggplot is extended in the accompanying feasts package to work well with tsibbles:
feasts::autoplot(Value) + geom_point(na.rm = TRUE)