我构建了一个简单的线性回归模型,并使用该模型生成了一些预测值。但是,我更感兴趣的是在图表上将其可视化,但我不知道如何添加图例以将原始值mpg值更改为“黑色”,并将新值预测为值为“红色”。如何使用ggplot2将新图例添加到复杂散点图
在本实施例中使用的数据是从数据集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")
散点图
几乎相同的 “一个班轮” 我正要张贴:)'mtcars%>%选择(MPG,.fitted = hp)%> mutate(预测= 0)%>%bind_rows(mutate(new_hp,predicted = 1))%>%ggplot(aes(mpg,.fitted))+ geom_point(aes(color = as.factor预测)))+ geom_smooth(method =“lm”,se = FALSE)+ scale_color_manual(values = c(“black”,“red”),name =“predicted”)+ labs(y =“hp”)' – neilfws
@neilfws我喜欢你的“单行”。感谢分享。 – www
感谢您分享您的代码。我非常感谢你的帮助 – Tuyen