rggplot2time-seriesdecomposition

Arrange decomposition plot vertically


I have the following daily data series:

> library(stR)
> library(forecast)
> library(ggplot2)
> spain_daily
# A tibble: 1,096 × 2
   Date       Daily_Load
   <date>          <dbl>
 1 2022-01-01     20872.
 2 2022-01-02     22729.
 3 2022-01-03     27358.
 4 2022-01-04     28262.
 5 2022-01-05     28048.
 6 2022-01-06     24182.
 7 2022-01-07     27763.
 8 2022-01-08     26870.
 9 2022-01-09     25605.
10 2022-01-10     29879.
# ℹ 1,086 more rows
# ℹ Use `print(n = ...)` to see more rows

I can decompose the series using ggplot2:

autoplot(mstl(msts(spain_daily$Daily_Load, seasonal.periods = c(7, 365.25))))

And that results in this:

decomp1

However, I would prefer to do it in base R:

fit <- AutoSTR(msts(spain_daily$Daily_Load, seasonal.periods = c(7, 365.25)))
plot(components(fit))

But I get this result:

decomp2

How do I remove the two-column plots and align all the five series vertically, as in the ggplot2-based solution?

Thank you in advance.


Solution

  • Your call to plot(components(fit)) is actually using plot.ts under the hood. That function accepts nc= as an argument to indicate the number of columns to use.

    ### note the "ts" here, indicating it's using `plot.ts` underneath
    class(components(fit))
    # [1] "mts"    "ts"     "matrix" "array" 
    

    I don't have spain_daily, so I'll demonstrate with taylor. The msts(...) is taken from ?msts as an example.

    library(stR)
    library(forecast)
    library(ggplot2)
    tay <- msts(taylor, seasonal.periods=c(2*24,2*24*7,2*24*365), start=2000+22/52)
    autoplot(mstl(tay))
    # Warning in mstl(tay) :
    #   Dropping seasonal components with fewer than two full periods.
    

    ggplot2 autoplot of the taylor data

    fit <- AutoSTR(tay) # this took a minute or two
    plot(components(fit))
    

    base plot with two columns

    plot(components(fit), nc=1)
    

    base plot with one column