Time series forecasting allows one to project future trends based on historical patterns.


Time series forecasting allows one to project future trends based on historical patterns. Whether tracking emergency department visits, seasonal disease outbreaks, or economic metrics, robust forecasting provides actionable foresight.
In this guide, we will walk through how to fit an ETS (Error, Trend, Seasonality) time series model in R, align historical data with future predictions, and construct a multi-layered, publication-ready visualisation using ggplot2.
Time series data can typically be decomposed into three underlying components:
The ETS framework evaluates these components to generate reliable point forecasts and prediction intervals. An additive ETS model (ETS(A,A,A)) assumes that noise, trend, and seasonal components add together linearly, making it particularly suitable for consistent seasonal counts such as monthly healthcare admissions or case numbers.
To follow along, you will need a few core R packages for time series modelling, date manipulation, and visualisation:
forecast: provides functions for fitting ETS models and calculating confidence intervals.lubridate: simplifies handling month end-dates and annual roll-overs.dplyr: facilitates efficient data manipulation.ggplot2: the industry standard for creating layered, custom visualisations in R.1# Install packages if you haven't already:2# if (!require("forecast")) install.packages("forecast")3# if (!require("lubridate")) install.packages("lubridate")4# if (!require("dplyr")) install.packages("dplyr")5# if (!require("ggplot2")) install.packages("ggplot2")67library(forecast) # Time series modelling and forecasting8library(lubridate) # Date sequences and time handling9library(dplyr) # Data wrangling10library(ggplot2) # Publication-ready graphics
First, we generate a synthetic dataset mimicking 11 years (132 months) of emergency case counts from 2014 to 2024. We then convert this data into an R ts (time series) object with a monthly frequency (frequency = 12).
1# --- Generate Synthetic Dataset (2014–2024) ---2set.seed(42)3dates_seq <- seq(as.Date("2014-01-01"), as.Date("2024-12-01"), by = "month")4t <- 1:length(dates_seq)56# Simulate underlying trend, monthly seasonality, and noise7seasonal_effect <- 80 * sin(2 * pi * t / 12) + 40 * cos(2 * pi * t / 12)8trend_effect <- 1.2 * t9noise <- rnorm(length(dates_seq), mean = 0, sd = 35)1011cases_simulated <- round(620 + trend_effect + seasonal_effect + noise)1213m_dat <- data.frame(14 Year = as.integer(format(dates_seq, "%Y")),15 Month = factor(format(dates_seq, "%b"), levels = month.abb),16 Cases = as.integer(cases_simulated)17)1819# Inspect dataset structure20str(m_dat)2122# --- Convert to Time Series Object ---23ts_data <- ts(m_dat$Cases, start = c(2014, 1), frequency = 12)
Next, we fit an additive ETS model (ETS(A,A,A)) to capture error, trend, and seasonal components. We then project these patterns 60 months (5 years) into the future.
1# --- Fit ETS Model ---2ets_model <- ets(ts_data, model = "AAA")34# --- Generate 5-Year Forecast (60 months) ---5forecasted <- forecast(ets_model, h = 60)67# Extract numerical vectors for observed, fitted, and forecasted values8historical_data <- as.numeric(ts_data)9fitted_data <- as.numeric(fitted(ets_model))1011forecast_values <- as.numeric(forecasted$mean)12lower_80 <- as.numeric(forecasted$lower[, 1])13upper_80 <- as.numeric(forecasted$upper[, 1])14lower_95 <- as.numeric(forecasted$lower[, 2])15upper_95 <- as.numeric(forecasted$upper[, 2])
To plot both historical data and future predictions seamlessly in ggplot2, we construct an aligned date sequence that handles year-end roll-overs and aligns each data point to the last day of its respective month.
1# --- Historical Date Sequence ---2start_date <- as.Date("2014-01-01")3historical_dates <- seq(start_date, by = "month", length.out = length(historical_data))4historical_dates <- ceiling_date(historical_dates, "month") - days(1) # End of month56# --- Forecast Date Sequence ---7last_date <- historical_dates[length(historical_dates)]8last_year <- year(last_date)9last_month <- month(last_date)1011forecast_dates <- c()12for (i in 1:length(forecast_values)) {13 new_month <- last_month + i14 new_year <- last_year1516 # Handle year rollover17 while (new_month > 12) {18 new_month <- new_month - 1219 new_year <- new_year + 120 }2122 temp_date <- as.Date(paste(new_year, new_month, "01", sep = "-"))23 month_end <- ceiling_date(temp_date, "month") - days(1)24 forecast_dates <- c(forecast_dates, month_end)25}2627forecast_dates <- as.Date(forecast_dates, origin = "1970-01-01")28all_dates <- c(historical_dates, forecast_dates)2930# --- Combine into Unified Data Frame ---31df1 <- data.frame(32 Date = all_dates,33 Data = c(historical_data, rep(NA, length(forecast_values))),34 Fitted = c(fitted_data, rep(NA, length(forecast_values))),35 Forecast = c(rep(NA, length(historical_data)), forecast_values),36 Low80 = c(rep(NA, length(historical_data)), lower_80),37 High80 = c(rep(NA, length(historical_data)), upper_80),38 Low95 = c(rep(NA, length(historical_data)), lower_95),39 High95 = c(rep(NA, length(historical_data)), upper_95)40)4142# Connect the gap between historical observed data and the forecast origin43lastNonNAinData <- max(which(complete.cases(df1$Data)))44df1[lastNonNAinData, !(colnames(df1) %in% c("Data", "Fitted", "Date"))] <- df1$Data[lastNonNAinData]
Using ggplot2, we layer the historical observations, model fit, point forecast, and shaded 80% and 95% confidence intervals into a clean, readable figure (Figure 1).
1# --- Build Plot ---2plt1 <- ggplot(df1, aes(x = Date)) +3 ggtitle("Seasonality of Emergency Cases and 5-Year ETS Forecast") +4 xlab("Year") +5 ylab("Total Cases") +67 # Shaded Confidence Intervals8 geom_ribbon(aes(ymin = Low95, ymax = High95, fill = "95%"), alpha = 0.3) +9 geom_ribbon(aes(ymin = Low80, ymax = High80, fill = "80%"), alpha = 0.3) +10 scale_fill_manual(11 name = "Confidence Intervals",12 values = c("95%" = "#A2C4EC", "80%" = "#2B5B84")13 ) +1415 # Lines and Points16 geom_point(aes(y = Data, colour = "Data"), size = 1.5) +17 geom_line(aes(y = Data, group = 1, colour = "Data"), linetype = "solid", linewidth = 1) +18 geom_line(aes(y = Fitted, group = 2, colour = "Fitted"), linewidth = 1) +19 geom_line(aes(y = Forecast, group = 3, colour = "Forecast"), linewidth = 1, linetype = "solid") +2021 # Colour Schemes22 scale_colour_manual(23 name = "Legend",24 labels = c("Observed Data", "Model Fit", "Forecast"),25 values = c(Data = "#4A90E2", Fitted = "#50E3C2", Forecast = "#203659")26 ) +2728 # Axis Formatting29 scale_x_date(date_breaks = "1 year", date_labels = "%Y") +30 scale_y_continuous(breaks = seq(from = 0, to = 1500, by = 100)) +3132 # Legend Ordering and Theme33 guides(colour = guide_legend(order = 1), fill = guide_legend(order = 2)) +34 theme_bw(base_size = 14) +35 theme(36 axis.text.x = element_text(angle = 45, hjust = 1),37 axis.title = element_text(size = 16),38 plot.title = element_text(size = 18, hjust = 0.5)39 )4041print(plt1)
Finally, we save the resulting plot as a high-resolution image and export the underlying numerical table containing point predictions and uncertainty intervals for reporting.
1# --- Export High-Resolution Plot ---2ggsave("ETS_forecast_emergency_cases.png", plt1, width = 13, height = 6, dpi = 300)34# --- Export Forecast Table ---5write.csv(df1, "ets_forecasted_table.csv", row.names = FALSE)

Figure 1. Historical monthly emergency case numbers (2014–2024) and 5-year ETS model forecast (2025–2029).
The plot displays 11 years of historical monthly emergency case counts (2014–2024) alongside a 5-year additive ETS model forecast projecting through 2029:
By combining forecast::ets() with custom ggplot2 layering, you can transform raw monthly counts into rigorous, publication-ready forecasts. Shading prediction intervals explicitly communicates uncertainty, allowing researchers and stakeholders to evaluate projected outcomes alongside historical variations.

Molecular biology, agronomy, and experimental design — translating wet-lab questions into sound statistical plans.
LinkedIn →Book a free 20-minute consultation. We'll scope your analysis and tell you exactly what it takes to publish.