Based on your requirements, you can use the ggplot2 package in R to create a plot that combines both observed data and forecasted values for each time step. Here is an example code snippet that should help:
# Load necessary libraries
library(ggplot2)
library(lubridate)
# Assuming your data is named 'data_frame' and it has two columns: 'dates' (of type Date) and 'datafcst'
# Also assuming your forecasted values are in a column named 'forecast'
# Create a new dataframe that combines both observed data and forecasted values
new_data <- data.frame(
dates = c(data_frame$dates, as.Date(paste0("1900-01-01 + ", format(c(1:24), "%Y-%m-%d %H:%M:%S"))),
forecast,
date_forecast = paste0("1900-01-01 + ", format(c(1:24), "%Y-%m-%d %H:%M:%S"))
)
# Convert the 'forecast' column to a datetime object
new_data$forecast <- as.POSIXct(new_data$forecast, origin = "1900-01-01")
# Create a new dataframe that combines both observed data and forecasted values for each date
data_combined <- data.frame(
dates = unique(c(data_frame$dates, new_data$date_forecast)),
datafcst = c(data_frame$datafcst, new_data$forecast),
data_observed = ifelse(is.na(new_data$forecast), data_frame$datafcst, NA)
)
# Create the ggplot2 plot
ggplot(data_combined, aes(x = dates, y = datafcst)) +
geom_point() +
geom_line(aes(group = factor(data_observed)), linetype = "dashed") +
labs(title = "Forecasted and Observed Values Over Time", x = "Date", y = "Value")
This code creates a new dataframe new_data that combines both observed data and forecasted values. It then converts the ‘forecast’ column to a datetime object and creates another dataframe data_combined that has unique dates for each observation.
Finally, it uses the ggplot2 package to create a plot with points representing both observed data and forecasted values. The geom_line() function is used to draw a dashed line for the observed values, making them distinguishable from the forecasted values.
Note: You need to adjust this code according to your actual data and data structure.
Last modified on 2025-02-19