我構建了一個簡單的線性迴歸模型,並使用該模型生成了一些預測值。但是,我更感興趣的是在圖表上將其可視化,但我不知道如何添加圖例以將原始值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