R squared regression in r with ggplot

# Install and load necessary packages
install.packages("ggplot2")
library(ggplot2)

# Generate sample data
set.seed(123)
x <- rnorm(100)
y <- 2 * x + rnorm(100)

# Perform linear regression
fit <- lm(y ~ x)

# Extract R squared value
rsquared <- summary(fit)$r.squared

# Create a scatter plot with regression line
ggplot(data = data.frame(x, y), aes(x = x, y = y)) +
  geom_point() +
  geom_smooth(method = "lm", se = FALSE, color = "blue") +
  labs(title = paste("Scatter Plot with Regression Line (R^2 =", round(rsquared, 3), ")"))