rggplot2time-seriesforecast

How to insert text label on faceted time series data using the forecast package in R?


I am doing time series analysis in R using the forecast package. The forecast::autoplot() creates a ggplot object.

I have two questions about plotting decomposed series:

  1. How do I place text in the trend panel (next to the vertical red line). Using ggplot or other packages?
  2. How can I rename the "data" panel to be capitalized as "Data"?

Here is my code:

library(forecast)    

# Load in AirPassengers time series
data("AirPassengers")

# Decomopose time series
decomposed_ts <- decompose(AirPassengers)

# Plot decomposed time series
forecast::autoplot(decomposed_ts) + geom_vline(xintercept = 1954, colour = "red")

Screenshot of two questions

For Q1, I tried to use annotate() but it places the same text labels on each facet, whereas I only want one label on only the trend panel (see screenshot). I also tried to use the ggtext package, but could not get it to work. I couldn't figure out what the faceted variable is because forecast::autoplot() automatically created the faceting.

For Q2. I saved the plot as a variable i.e. myPlot <- forecast::autoplot(decomposed_ts) + geom_vline(xintercept = 1954, colour = "red"). I then tried myPlot$ looking for where the "data" facet is named.


Solution

  • You can add geom_text to the original auto_plot:

    annotation <- data.frame(
      x = c(1950),
      y = c(250),
      parts = c("trend"),
      label = c("label 1")
    )
    
    forecast::autoplot(decomposed_ts) +
      geom_vline(xintercept = 1954, colour = "red") +
      geom_text(data = annotation, aes(x = x, y = y, label = label)) 
    

    Adding a layer to autoplot