Search code examples
rggplot2time-seriesdecompositionautoplot

How to print consistent R visualizations of decomposed time series using autoplot()


I have an R script that sometimes produces plots of decomposed time series one way and sometimes another way. I can't figure out if it's using two different autoplot() functions or what else could be making this happen. It is seemingly random: one week I get one format, the next week I get the other one.

I prefer the plot with the title "Decomposition of additive time series." Can anyone tell why running the same script gives me different results?

Thanks

library(pacman)
p_load(tidyverse, janitor, lubridate, forecast)

# import data
df <-
  clean_names(
    read_csv("data.csv")) %>% 
  mutate(date = mdy(date)) %>% 
  select(-dpb)

# create monthly df
df_monthly <- df %>%
  mutate(month = floor_date(date, unit = "month")) %>% 
  group_by(month) %>% 
  summarise(bbl = sum(bbl),
            rev = sum(rev)) %>% 
  mutate(dpb = rev/bbl) %>% 
  select(month, dpb)

# Decompose time series
t <- ts(data = df_monthly[,-1], start = c(2014, 1, 1), frequency = 12)

d <- decompose(t, type = "additive")

# Plot decomposed time series
p <- autoplot(d)

print(p)

I have tried specifying ggplot2::autoplot() and forecast::autoplot() thinking that would answer my question, but to no avail. Currently they are both producing the plot I don't want.

don't want do want


Solution

  • Almost certainly the differences arise because of the packages you have loaded. The code in your question should use the autoplot.decomposed.ts() function from the forecast package. But if you have loaded other packages, it is possible one of them has a similar function that is being used instead. In particular, the ggfortify package has an autoplot.decomposed.ts() function, so if you load ggfortify after you load forecast, you will get a different plot.

    You can specify which one you want be prefixing the function with the package name. For example

    forecast:::autoplot.decomposed.ts(d)
    

    Because the specific method is not exported, you need 3 dots, not 2 dots.