Linear Regression

This R script reads a CSV file containing bare ground cover and precipitation data, fits a linear regression model, and then visualizes the results. It calculates the slope, intercept, R² value, and p-value, plots both a scatter plot and a regression line with confidence intervals, and finally exports the figure as an SVG file for easy sharing or embedding.

# Install and load required packages --------------------------------------

# Uncomment the next 3 lines if you need to install these packages

# install.packages("ggplot2")

# install.packages("dplyr")

# install.packages("svglite")


# Load necessary libraries

library(ggplot2)

library(dplyr)

library(svglite)


# Load Data ----------------------------------------------------------------

data <- read.csv("C:/Users/"# Replace with actual file path


# Check the structure of the data to ensure variables are correct

str(data)


# Data Processing ----------------------------------------------------------

# Fit linear model

model <- lm(BGR ~ NOAA_Precip, data = data)


# Extract model details: slope, intercept, R-squared, and p-value for slope

slope <- coef(model)[2]

intercept <- coef(model)[1]

r_squared <- summary(model)$r.squared

p_value <- summary(model)$coefficients[2, 4# p-value for the slope coefficient


# Set p-value text based on the condition

p_value_text <- ifelse(p_value < 0.01, "<.01", round(p_value, digits = 2))


# Create equation text for display

equation_text <- paste0("y = ", round(slope, 2), "x + ", round(intercept, 2),

                        ", R² = ", round(r_squared, 2),

                        ", p = ", p_value_text)


# Determine axis limits to make scales match

max_value <- max(data$BGR, data$NOAA_Precip, na.rm = TRUE)

min_value <- min(data$BGR, data$NOAA_Precip, na.rm = TRUE)


# Save the plot as an SVG file

svglite("BGvsPrecipitation.svg")


# Plot --------------------------------------------------------------------

print(ggplot(data, aes(x = NOAA_Precip, y = BGR)) +

        # Scatter plot points

        geom_point(color = "black") +

        # Trendline with confidence interval

        geom_smooth(method = "lm", color = "dodgerblue", fill = "dodgerblue", se = TRUE) +

        # Add 1:1 perfect fit line

        geom_abline(slope = 1, intercept = 0, linetype = "dashed", color = "black") +

        # Set axis labels and title

        labs(title = "Bare Ground vs Precipitation Linear Regression", x = "NOAA Annual Precipitation in Inches", y = "RAP Bare Ground Percent Cover") +

        # Add text annotation with model details on the top left

        annotate("text", x = min_value + 5, y = max_value - 5, label = equation_text,

                 hjust = 0, vjust = 1, size = 4, color = "black", parse = FALSE) +

        # Apply minimal theme

        theme_minimal() +

        # Remove legend

        theme(legend.position = "none"))


dev.off()