【问题标题】:How to add geom_point() to autolayer() line?如何将 geom_point() 添加到 autolayer() 行?
【发布时间】:2019-09-04 05:05:39
【问题描述】:

尝试将 geom_points 添加到 autolayer() 行(图片中的“拟合”),这是 Rob Hyndmans 预测包中 ggplot2 的 autoplot() 的 wrapper 一部分(ggplot2 中也有一个基本的 autoplot/autolayer同样可能适用于那里)。

问题是(我不是 ggplot2 专家,并且 autoplot 包装器使它变得更棘手) 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

【问题讨论】:

    标签: r ggplot2 forecast


    【解决方案1】:

    这似乎有效:

    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

    【讨论】:

    • 成功了,谢谢@amoeba!技术也扩展到预测元素。在 autolayer() 旁边插入一个普通的(但预编译的)geom_point() 很方便。如您所说,直接扩展后者会很好,但由于我们不了解内部结构,因此这是一个很好的解决方案。
    猜你喜欢
    • 2020-05-25
    • 1970-01-01
    • 2015-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多