Here is the dput for the dataset I'm working with:
structure(list(X = c(18, 19, 20, 17, 8, 15, 14, 16, 18, 14, 16,
13, 16, 17, 10, 18, 19, 25, 18, 13, 18, 16, 11, 17, 15, 18, 19,
16, 20, 17, 8, 18, 15, 14, 18, 14, 16, 13, 16), Y = c(15, 13,
14, 22, 2, 11, 15, 11, 20, 17, 20, 17, 20, 14, 21, 10, 13, 16,
12, 11, 13, 10, 4, 16, 18, 15, 10, 13, 14, 17, 2, 11, 15, 11,
20, 17, 14, 7, 16), Z = c(32, 42, 37, 34, 32, 39, 44, 49, 36,
31, 36, 37, 37, 45, 46, 48, 36, 42, 36, 25, 36, 39, 26, 32, 33,
38, 33, 44, 46, 34, 32, 39, 44, 49, 36, 31, 36, 37, 37)), class = "data.frame", row.names = c(NA,
-39L))
So before when I ran linear regressions in R, I would use a simple code like this:
library(ggplot2)
library(ggpmisc)
ggplot(data = hw_data,
aes(x=X,
y=Y))+
geom_point()+
geom_smooth(method = lm)+
stat_poly_eq(formula = simple_model,
aes(label = paste(..eq.label.., ..rr.label..,
sep = "~~~~~~")))
This would give me a graph with this kind of equation label:
However, I'm trying to run a multiple linear regression and a hierarchal regression, but when I try to add in a third variable, I'm not entirely sure how to 1) get the third variable (Z) to graph as a regression line and 2) get an equation that fits the model on the graph. What I'm looking for is something like this:
The two models I need to graph are (Y ~ X + Z) and (Y ~ X * Z). The best I've come up with so far is this:
# One predictor model:
hw_regression_simple <- lm(Y ~ X,
data = hw_data)
# Two predictor model:
hw_regression_two_factors <- lm(Y ~ X + Z,
hw_data)
# Interaction model:
hw_regression_interaction <- lm(Y ~ X * Z,
hw_data)
# Comparison of models:
summary(hw_regression_simple)
summary(hw_regression_two_factors)
summary(hw_regression_interaction)
model <- Y ~ X * Z
ggplot(data = hw_data,
aes(x=X,
y=Y,
color=Z))+
geom_point()+
geom_smooth(method = lm)+
labs(title = "X, Y, and Z Interactions")+
stat_poly_eq()
Which gives me this graph with an R-squared and some coloration of the scatterplot, but otherwise doesn't give as much info as I'd like. How can I fix this to look more like the models I'm looking for?