如何将 geom_point() 添加到 autolayer() 行?

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

尝试将 geom_points 添加到 autolayer() 行(图片中的 "fitted"),这是 Rob Hyndmans 预测包中 ggplot2 的 autoplot() 的 wrapper 部分( ggplot2 中也有一个基础 autoplot/autolayer,所以同样适用于那里)。

问题是(我不是 ggplot2 专家,autoplot wrapper 让它变得更棘手)geom_point() 适用于主调用,但我如何应用类似于 autolayer(拟合值) ?

像普通 geom_line() 一样尝试过 type="b" 但它不是 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

这似乎有效:

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))

可能有一种方法可以让 forecast::autolayer 直接做你想做的事,但这个解决方案有效。如果您希望图例看起来正确,您需要将输入数据和拟合值合并为一个 data.frame.