如何绘制回归线和R中观察到的和预测的散点图

时间:2013-04-25 20:18:30

标签: r data-visualization

如何在R中绘制观察到的vs预测的散点图?我还想在其中显示回归线。

library(car)
summary(Prestige)
head(Prestige)
testidx <- which(1:nrow(Prestige)%%4==0)
prestige_train <- Prestige[-testidx,]
prestige_test <- Prestige[testidx,]

model <- glm(prestige~., data=prestige_train)
# Use the model to predict the output of test data 
prediction <- predict(model, newdata=prestige_test)
# Check for the correlation with actual result
plot(prediction, prestige_test$prestige)

编辑:

abline(model)

上述功能abline似乎不起作用。它确实画了一条线,但似乎是不正确的。

谢谢

1 个答案:

答案 0 :(得分:1)

当Hadley Wickham存在一个更美丽(可能更有说服力)的解释时,我认为我不需要完整地写出答案。它是here(第一部分)和here(第二部分,更高级的部分)。

编辑:我很抱歉从一开始就没有给出更具体的答案。这里可以如何制作情节:

# define training sample
sample <- sample(nrow(Prestige),40,replace=FALSE)

training.set <- Prestige[sample,]
test.set <- Prestige[-sample,]
model <- glm(prestige ~ .,data=training.set)
# getting predicted values
test.set$predicted <- predict(model,newdata=test.set)

# plotting with base plot 
with(test.set,plot(prestige,predicted))
# plotting with ggplot2
require(ggplot2)
qplot(prestige,predicted,data=test.set)

希望这能回答你的问题。

P.S。问题确实更适合SO,它会在几分钟内回答:)