BioMatikaBioMatika
← BlogMethods

How to model and forecast time series data in R: from raw data to publication-ready charts

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

Dr. Gabija Vaitkevičiūtė
Dec 2026 · 5 min read
Line chart of monthly emergency cases 2014–2024 with the fitted ETS model and a 5-year forecast to 2029 with 80% and 95% confidence bands
Figure 1. Historical monthly emergency case numbers (2014–2024) and 5-year ETS model forecast (2025–2029).

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.

1. What is ETS forecasting and why should researchers use it?

Time series data can typically be decomposed into three underlying components:

  • Error (E): the residual noise or unexpected variation in the observations.
  • Trend (T): the long-term direction of the data (increasing, decreasing, or stationary).
  • Seasonality (S): periodic fluctuations that repeat over a fixed calendar cycle (such as annual winter spikes).

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.

2. R packages we'll be using

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")
6
7library(forecast) # Time series modelling and forecasting
8library(lubridate) # Date sequences and time handling
9library(dplyr) # Data wrangling
10library(ggplot2) # Publication-ready graphics

3. Step-by-step implementation

Step 1. Generate synthetic data and create time series object

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)
5
6# Simulate underlying trend, monthly seasonality, and noise
7seasonal_effect <- 80 * sin(2 * pi * t / 12) + 40 * cos(2 * pi * t / 12)
8trend_effect <- 1.2 * t
9noise <- rnorm(length(dates_seq), mean = 0, sd = 35)
10
11cases_simulated <- round(620 + trend_effect + seasonal_effect + noise)
12
13m_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)
18
19# Inspect dataset structure
20str(m_dat)
21
22# --- Convert to Time Series Object ---
23ts_data <- ts(m_dat$Cases, start = c(2014, 1), frequency = 12)

Step 2. Fit ETS model and generate 5-year forecast

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")
3
4# --- Generate 5-Year Forecast (60 months) ---
5forecasted <- forecast(ets_model, h = 60)
6
7# Extract numerical vectors for observed, fitted, and forecasted values
8historical_data <- as.numeric(ts_data)
9fitted_data <- as.numeric(fitted(ets_model))
10
11forecast_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])

Step 3. Align historical and forecast dates

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 month
5
6# --- Forecast Date Sequence ---
7last_date <- historical_dates[length(historical_dates)]
8last_year <- year(last_date)
9last_month <- month(last_date)
10
11forecast_dates <- c()
12for (i in 1:length(forecast_values)) {
13 new_month <- last_month + i
14 new_year <- last_year
15
16 # Handle year rollover
17 while (new_month > 12) {
18 new_month <- new_month - 12
19 new_year <- new_year + 1
20 }
21
22 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}
26
27forecast_dates <- as.Date(forecast_dates, origin = "1970-01-01")
28all_dates <- c(historical_dates, forecast_dates)
29
30# --- 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)
41
42# Connect the gap between historical observed data and the forecast origin
43lastNonNAinData <- max(which(complete.cases(df1$Data)))
44df1[lastNonNAinData, !(colnames(df1) %in% c("Data", "Fitted", "Date"))] <- df1$Data[lastNonNAinData]

Step 4. Visualise the forecast with custom confidence intervals

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") +
6
7 # Shaded Confidence Intervals
8 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 ) +
14
15 # Lines and Points
16 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") +
20
21 # Colour Schemes
22 scale_colour_manual(
23 name = "Legend",
24 labels = c("Observed Data", "Model Fit", "Forecast"),
25 values = c(Data = "#4A90E2", Fitted = "#50E3C2", Forecast = "#203659")
26 ) +
27
28 # Axis Formatting
29 scale_x_date(date_breaks = "1 year", date_labels = "%Y") +
30 scale_y_continuous(breaks = seq(from = 0, to = 1500, by = 100)) +
31
32 # Legend Ordering and Theme
33 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 )
40
41print(plt1)

Step 5. Export figures and forecast tables

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)
3
4# --- Export Forecast Table ---
5write.csv(df1, "ets_forecasted_table.csv", row.names = FALSE)
Line chart of monthly emergency cases 2014–2024 with the fitted ETS model and a 5-year forecast to 2029 with 80% and 95% confidence bands

Figure 1. Historical monthly emergency case numbers (2014–2024) and 5-year ETS model forecast (2025–2029).

Interpreting the results

The plot displays 11 years of historical monthly emergency case counts (2014–2024) alongside a 5-year additive ETS model forecast projecting through 2029:

  • Historical alignment and model fit. The fitted model line (cyan) tracks the observed historical data (blue) closely across the 2014–2024 timeframe. The model effectively captures both the baseline upward trend in total cases (climbing from ~600–700 in earlier years to >800 by 2024) and the consistent intra-annual seasonal fluctuations.
  • Projected seasonality and upward trend. The 5-year point forecast (dark blue) extends these learned historical dynamics into 2025–2029. It predicts that annual peaks will continue to rise incrementally over the years — approaching 900 cases per peak towards 2029 — while preserving the predictable seasonal fluctuations.
  • Quantifying uncertainty. The shaded confidence bands illustrate the range of expected variation over time. The inner 80% prediction interval (darker blue) provides a likely estimate for routine personnel planning, while the outer 95% interval (lighter blue) accounts for potential wider anomalies. As expected with time series models, the prediction intervals widen slightly further into the future, reflecting increasing uncertainty over longer time horizons.

Summary

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.

View the full code.

#r#time-series#ets#forecasting#ggplot2
Written by
Dr. Gabija Vaitkevičiūtė
Research Scientist

Molecular biology, agronomy, and experimental design — translating wet-lab questions into sound statistical plans.

LinkedIn →
WE HELP SCIENTISTS BE SCIENTISTS

Let's get your data publication-ready

Book a free 20-minute consultation. We'll scope your analysis and tell you exactly what it takes to publish.

Book a consultation →