# Create beautiful visualization
poly_plot <- ggplot(data_poly, aes(x = x, y = y)) +
# Data points and regression lines
geom_point(color = "#3498DB", size = 2.5, alpha = 0.7) +
geom_line(data = grid_poly, aes(x = x, y = linear, color = "Linear"), size = 1) +
geom_line(data = grid_poly, aes(x = x, y = quadratic, color = "Quadratic"), size = 1) +
geom_line(data = grid_poly, aes(x = x, y = cubic, color = "Cubic"), size = 1) +
# Colors and annotations
scale_color_manual(name = "Model Type",
values = c("Linear" = "#E74C3C", "Quadratic" = "#2ECC71","Cubic" = "#9B59B6")) +
annotate("text", x = -4, y = max(y_poly) - 1,
label = paste0("Linear R² = ", r2_linear), color = "#E74C3C", size = 4, hjust = 0) +
annotate("text", x = -4, y = max(y_poly) - 2,
label = paste0("Quadratic R² = ", r2_quadratic), color = "#2ECC71",size = 4,hjust=0)+
annotate("text", x = -4, y = max(y_poly) - 3,
label = paste0("Cubic R² = ", r2_cubic), color = "#9B59B6", size = 4,
hjust = 0) +
# Labels and styling
labs(title = "Polynomial Regression Models",
subtitle = "Comparing linear, quadratic, and cubic fits",
x = "X Variable", y = "Y Variable") +
theme_minimal() +
theme(legend.position = "bottom")