如何用ggplot在真实时间序列上绘制LSTM股票预测值?
The issue with your current ggplot code is that it aligns all prediction sequences to the start of the x-axis instead of shifting them to their correct positions (like the Python code does with padding). Here's how to fix it by properly positioning each prediction segment:
Step 1: Prepare the Data Correctly
We need to create a combined data frame where:
- The true test data is a continuous sequence from x=1 to x=length(y_test)
- Each prediction sequence is shifted to start at its correct position (i*prediction_len + 1 for the i-th sequence)
- We add a
groupidentifier to ensure ggplot draws each prediction as a separate line segment (not connecting them to each other)
library(dplyr) library(ggplot2) library(purrr) # For map_dfr function # Define prediction length (matches your function parameter) prediction_len <- 50 # Create true test data frame true_data <- tibble( x = 1:length(y_test), value = unlist(y_test), series_type = "True Data", group_id = "True_Data" ) # Create prediction data frame with correct positioning prediction_data <- purrr::map_dfr(seq_along(predictions), function(seq_idx) { # Calculate starting position for this prediction sequence start_x <- (seq_idx - 1) * prediction_len + 1 end_x <- start_x + prediction_len - 1 tibble( x = start_x:end_x, value = predictions[[seq_idx]], series_type = "Prediction", group_id = paste0("Pred_", seq_idx) ) }) # Combine true and prediction data plot_data <- dplyr::bind_rows(true_data, prediction_data)
Step 2: Plot with ggplot2
Now we can plot the data, using series_type for color and group_id to ensure proper line segments:
ggplot(plot_data, aes(x = x, y = value, color = series_type, group = group_id)) + geom_line(linewidth = 0.8) + labs( title = "S&P 500 Normalized Price: Predictions vs True Data", x = "Time Step", y = "Normalized Closing Price", color = "Series" ) + theme_minimal() + theme(plot.title = element_text(hjust = 0.5))
Why Your Original Code Failed
Your original approach using cbind.fill and gather aligned all prediction sequences to the first 50 x-values, causing all predictions to overlap at the start of the plot. By explicitly calculating the correct x-position for each prediction sequence and adding a group identifier, we replicate the Python code's behavior where each prediction shifts forward by prediction_len steps.
This will produce a plot identical to the Python version: the true data is a single continuous line, and each prediction segment starts at the correct position in the time series.
内容的提问来源于stack exchange,提问作者Mislav

