r - 如何在 R 中绘制预测子集?

标签 r plot data-science

我有一个简单的 R 脚本来创建基于文件的预测。 自 2014 年以来一直在记录数据,但我在尝试实现以下两个目标时遇到了麻烦:

  • 仅绘制预测信息的一个子集(从 11/2017 开始)。
  • 以特定格式包含月份和年份(即 Jun 17)。

这是 dataset 的链接在下面你会找到我到目前为止所做的代码。

# Load required libraries
library(forecast)
library(ggplot2)

# Load dataset
emea <- read.csv(file="C:/Users/nsoria/Downloads/AMS Globales/EMEA_Depuy_Finanzas.csv", header=TRUE, sep=';', dec=",")

# Create time series object
ts_fin <- ts(emea$Value, frequency = 26, start = c(2014,11))

# Pull out the seasonal, trend, and irregular components from the time series 
model <- stl(ts_fin, s.window = "periodic")

# Predict the next 3 bi weeks of tickets
pred <- forecast(model, h = 5)

# Plot the results
plot(pred, include = 5, showgap = FALSE, main = "Ticket amount", xlab = "Timeframe", ylab = "Quantity")

我感谢对我的两点和一个干净的情节的任何帮助和建议。

提前致谢。

编辑 01/10 - 第 1 期: 我为建议的代码添加了屏幕截图输出。 Plot1

编辑 01/10 - 第 2 期: 一旦使用以下代码进行转换,它就会以某种方式错过日期计数并弄乱结果。请查看两个屏幕截图并比较最后一个值。

Screenshot 1 Screenshot 2

最佳答案

使用 ggplot2 w/ggfortify 绘图、tidyverselubridatescales

    library(lubridate)
    library(tidyverse)
    library(scales)
    library(ggfortify)

    # Convert pred from list to data frame object
    df1 <- fortify(pred) %>% as_tibble()

    # Convert ts decimal time to Date class
    df1$Date <- as.Date(date_decimal(df1$Index), "%Y-%m-%d")
    str(df1)

    # Remove Index column and rename other columns
    # Select only data pts after 2017
    df1 <- df1 %>% 
      select(-Index) %>% 
      filter(Date >= as.Date("2017-01-01")) %>% 
      rename("Low95" = "Lo 95",
             "Low80" = "Lo 80",
             "High95" = "Hi 95",
             "High80" = "Hi 80",
             "Forecast" = "Point Forecast")
    df1

    ### Updated: To connect the gap between the Data & Forecast, 
    # assign the last non-NA row of Data column to the corresponding row of other columns
    lastNonNAinData <- max(which(complete.cases(df1$Data)))
    df1[lastNonNAinData, !(colnames(df1) %in% c("Data", "Fitted", "Date"))] <- df1$Data[lastNonNAinData]

    # Or: use [geom_segment](http://ggplot2.tidyverse.org/reference/geom_segment.html)

    plt1 <- ggplot(df1, aes(x = Date)) +   
      ggtitle("Ticket amount") +
      xlab("Time frame") + ylab("Quantity") +
      geom_ribbon(aes(ymin = Low95, ymax = High95, fill = "95%")) +
      geom_ribbon(aes(ymin = Low80, ymax = High80, fill = "80%")) +
      geom_point(aes(y = Data, colour = "Data"), size = 4) +
      geom_line(aes(y = Data, group = 1, colour = "Data"), 
                linetype = "dotted", size = 0.75) +
      geom_line(aes(y = Fitted, group = 2, colour = "Fitted"), size = 0.75) +
      geom_line(aes(y = Forecast, group = 3, colour = "Forecast"), size = 0.75) +
      scale_x_date(breaks = scales::pretty_breaks(), date_labels = "%b %y") +
      scale_colour_brewer(name = "Legend", type = "qual", palette = "Dark2") +
      scale_fill_brewer(name = "Intervals") +
      guides(colour = guide_legend(order = 1), fill = guide_legend(order = 2)) +
      theme_bw(base_size = 14)
    plt1

enter image description here

关于r - 如何在 R 中绘制预测子集?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48177663/

相关文章:

r - .Rnw 文件中的 Perl : the 'tilde' character

r - 替换一个数据框中的行(如果它们出现在另一数据框中)

python - 如何用不同颜色绘制同一 Pandas Series 列的不同部分?

machine-learning - 我在 RandomSearchCV 中不断收到 AttributeError

R:rgl 3D 绘制边界框面颜色和描边

R语言迭代gera斜体

matlab - 如何将(值的)标签添加到我的 MATLAB 图的顶部?

python - python scipy.stats 中的 norm.ppf 与 norm.cdf

python - 在 Seaborn 中为 python 创建一个箱线图 FacetGrid

r - 使用Knitr,R Markdown和Pandoc(Pander)的 block 引用