Search code examples
rggplot2forecast

How to add geom_point() to autolayer() line?


Trying to add geom_points to an autolayer() line ("fitted" in pic), which is a wrapper part of autoplot() for ggplot2 in Rob Hyndmans forecast package (there's a base autoplot/autolayer in ggplot2 too so same likely applies there).

Problem is (I'm no ggplot2 expert, and autoplot wrapper makes it trickier) the geom_point() applies fine to the main call, but how do I apply similar to the autolayer (fitted values)?

Tried type="b" like normal geom_line() but it's not an object param in autolayer().

require(fpp2)

model.ses <- ets(mdeaths, model="ANN", alpha=0.4)
model.ses.fc <- forecast(model.ses, h=5)

forecast::autoplot(mdeaths) +
  forecast::autolayer(model.ses.fc$fitted, series="Fitted") + # cannot set to show points, and type="b" not allowed
  geom_point() # this works fine against the main autoplot call

Fitted line needs points


Solution

  • This seems to work:

    library(forecast)
    library(fpp2)
    
    model.ses <- ets(mdeaths, model="ANN", alpha=0.4)
    model.ses.fc <- forecast(model.ses, h=5)
    
    # Pre-compute the fitted layer so we can extract the data out of it with 
    # layer_data()
    fitted_layer <- forecast::autolayer(model.ses.fc$fitted, series="Fitted")
    fitted_values <- fitted_layer$layer_data()
    
    plt <- forecast::autoplot(mdeaths) +
      fitted_layer +
      geom_point() +
      geom_point(data = fitted_values, aes(x = timeVal, y = seriesVal))
    
    

    enter image description here

    There might be a way to make forecast::autolayer do what you want directly but this solution works. If you want the legend to look right, you'll want to merge the input data and fitted values into a single data.frame.