Như tôi chỉ figured, trong trường hợp bạn có một mô hình trang bị trên nhiều hồi quy tuyến tính, giải pháp nêu trên sẽ không làm việc.
Bạn phải tạo dòng của mình theo cách thủ công dưới dạng khung dữ liệu có chứa giá trị được dự đoán cho khung dữ liệu ban đầu của bạn (trong trường hợp của bạn là data
).
Nó sẽ trông như thế này:
# 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)
