When you use geom_smooth() in ggplot2 with a specified span value for a training set, you're essentially fitting a loess smoother (or another smoothing method) to the training data. If you want to use the same span value to make predictions on a testing set, you need to:
- Fit the smoother explicitly (not just within
geom_smooth()) using loess() or another smoothing function.
- Apply the fitted model to the testing set to generate predictions.
Step-by-Step Approach
1. Fit the Smoother on the Training Data
Instead of just using geom_smooth(), fit the model explicitly with loess() (or another smoothing method) and store it.
# Example training data
train_data <- data.frame(x = rnorm(100), y = rnorm(100))
# Fit a loess model with a specified span
span_value <- 0.5 # Example span
loess_model <- loess(y ~ x, data = train_data, span = span_value)
2. Predict on the Testing Data
Now, use the fitted model to predict values for the testing set.
# Example testing data
test_data <- data.frame(x = seq(min(train_data$x), max(train_data$x), length.out = 50))
# Predict using the trained model
test_data$y_pred <- predict(loess_model, newdata = test_data)
3. Plot the Results (Optional)
You can visualize the predictions alongside the training data:
library(ggplot2)
ggplot() +
geom_point(data = train_data, aes(x = x, y = y)) +
geom_line(data = test_data, aes(x = x, y = y_pred), color = "red", linewidth = 1) +
labs(title = "Loess Smoothing with Predictions on Test Data")
Alternative: Using geom_smooth() with a Pre-Fitted Model
If you want to use geom_smooth() for plotting predictions (rather than fitting a new model), you can manually add the predictions to the test data and plot them:
ggplot() +
geom_point(data = train_data, aes(x = x, y = y)) +
geom_line(data = test_data, aes(x = x, y = y_pred), color = "red") +
labs(title = "Predictions from Pre-Fitted Loess Model")
Key Notes:
geom_smooth() is primarily for visualization, not for extracting predictions.
- To make predictions on new data, you need to fit the model explicitly (
loess(), lm(), etc.) and then use predict().
- If you're using a different smoothing method (e.g.,
method = "gam" in geom_smooth()), adjust the modeling function accordingly (e.g., mgcv::gam()).
Would you like help with a specific smoothing method or dataset?