อย่างที่ฉันเพิ่งคิดไปในกรณีที่คุณมีโมเดลที่พอดีกับการถดถอยเชิงเส้นหลาย ๆวิธีการแก้ปัญหาที่กล่าวถึงข้างต้นจะไม่ทำงาน
คุณต้องสร้างบรรทัดของคุณด้วยตนเองเป็น dataframe ที่มีค่าที่คาดการณ์ไว้สำหรับ dataframe เดิมของคุณ (ในกรณีของคุณdata
)
จะมีลักษณะดังนี้:
# read dataset
df = mtcars
# create multiple linear model
lm_fit <- lm(mpg ~ cyl + hp, data=df)
summary(lm_fit)
# save predictions of the model in the new data frame
# together with variable you want to plot against
predicted_df <- data.frame(mpg_pred = predict(lm_fit, df), hp=df$hp)
# this is the predicted line of multiple linear regression
ggplot(data = df, aes(x = mpg, y = hp)) +
geom_point(color='blue') +
geom_line(color='red',data = predicted_df, aes(x=mpg_pred, y=hp))

# this is predicted line comparing only chosen variables
ggplot(data = df, aes(x = mpg, y = hp)) +
geom_point(color='blue') +
geom_smooth(method = "lm", se = FALSE)
