【发布时间】:2017-11-16 03:22:06
【问题描述】:
我建立了一个简单的线性回归模型,并使用该模型生成了一些预测值。但是,我对在图表上可视化它更感兴趣,但我不知道如何添加图例以将原始 mpg 值突出显示为“黑色”和新的 predicted 值作为“红色”。
本例中使用的数据是 datasets 包中的 mtcars 数据集
library(ggplot2)
library(datasets)
library(broom)
# Build a simple linear model between hp and mpg
m1<-lm(hp~mpg,data=mtcars)
# Predict new `mpg` given values below
new_mpg = data.frame(mpg=c(23,21,30,28))
new_hp<- augment(m1,newdata=new_mpg)
# plot new predicted values in the graph along with original mpg values
ggplot(data=mtcars,aes(x=mpg,y=hp)) + geom_point(color="black") + geom_smooth(method="lm",col=4,se=F) +
geom_point(data=new_hp,aes(y=.fitted),color="red")
散点图
【问题讨论】: