你可以尝试这样的事情。更容易调试您的代码。
test <- data.frame(y=c(2,6,4,7,7,5), x1=c(5,4,2,5,5,4), x2=c(5,2,6,10,10,3),
x3=c(9,9,15,6,6,12))
reg=lm(y ~ x1 + x2 + x3, data = test)
# Add new columns to dataframe from regression
test$yhat <- reg$fitted.values
test$resid <- reg$residuals
# Create your x-variable column
test$X <-seq(nrow(test))
library(ggplot2)
library(reshape2)
# Columns to keep
keep = c("y", "yhat", "resid", "X")
# Drop columns not needed
test <-test[ , keep, drop=FALSE]
# Reshape for easy plotting
test <- melt(test, id.vars="X")
# Everything on the same plot
ggplot(test, aes(X,value, col=variable)) +
geom_point() +
geom_line()
对于不同的样子,你也可以用geom_smooth()
非常感谢取代
geom_line
!这很好,会找出第二轴! –