2017-06-14 246 views
3

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

enter image description here

散點圖

回答

3

這裏是一個想法。您可以將預測數據和觀測數據組合在同一數據框中,然後創建散點圖以生成圖例。以下代碼是現有代碼的擴展。

# Prepare the dataset 
library(dplyr) 

new_hp2 <- new_hp %>% 
    select(mpg, hp = .fitted) %>% 
    # Add a label to show it is predicted data 
    mutate(Type = "Predicted") 

dt <- mtcars %>% 
    select(mpg, hp) %>% 
    # Add a label to show it is observed data 
    mutate(Type = "Observed") %>% 
    # Combine predicted data and observed data 
    bind_rows(new_hp2) 

# plot the data 
ggplot(data = dt, aes(x = mpg, y = hp, color = factor(Type))) + 
    geom_smooth(method="lm", col = 4, se = F) + 
    geom_point() + 
    scale_color_manual(name = "Type", values = c("Black", "Red")) 
+2

幾乎相同的 「一個班輪」 我正要張貼:)'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

+0

@neilfws我喜歡你的「單行」。感謝分享。 – www

+0

感謝您分享您的代碼。我非常感謝你的幫助 – Tuyen

2

這裏是做不dplyr的另一種方式:

ggplot() + 
    geom_point(data = mtcars, aes(x = mpg, y = hp, colour = "Obs")) + 
    geom_point(data = new_hp, aes(x = mpg, y = .fitted, colour = "Pred")) + 
    scale_colour_manual(name="Type", 
         values = c("black", "red")) + 
    geom_smooth(data = mtcars, aes(x = mpg, y = hp), 
       method = "lm", col = 4, se = F) 
+0

非常感謝@ AK88。它真的幫助我擴大我的R技能 – Tuyen