2017-02-21 126 views
0

在以下示例中,我繼續從以下link開始,在這個示例中我們學習了創建對數迴歸模型的基本知識。多重對數迴歸模型ggplot2

data(mtcars) 
dat <- subset(mtcars, select=c(mpg, am, vs)) 
logr_vm <- glm(vs ~ mpg, data=dat, family=binomial) 
library(ggplot2) 
ggplot(dat, aes(x=mpg, y=vs)) + geom_point() + 
    stat_smooth(method="glm", method.args=list(family="binomial"), se=T) + 
    theme_bw() 

現在我想創建第二個日誌模型,我們預測新結果vs2。 如何使用ggplot2來顯示兩種不同顏色的模型?

dat$vs2 <- with(dat, ifelse(mpg > 20, 1, vs)) 

使得次級日誌模式是....

logr_vm2 <- glm(vs2 ~ mpg, data=dat, family=binomial) 

回答

3

ggplot本身擬合模型,你只有少數機型,你可以很容易地通過手動映射添加一個傳說aes中的顏色的型號名稱。其餘的將被照顧。

Addionally,我用geom_count而不是geom_point表明,我們這裏有重疊的值,並添加一些色彩來展現你不同的類別:

ggplot(dat, aes(x = mpg)) + 
    geom_count(aes(y = vs, col = mpg > 20), alpha = 0.3) + 
    stat_smooth(aes(y = vs, fill = 'm1'), col = 'black', 
       method = "glm", method.args = list(family = "binomial")) + 
    stat_smooth(aes(y = vs2, fill = 'm2'), col = 'black', 
       method = "glm", method.args = list(family = "binomial")) + 
    scale_size_area() + 
    scale_color_discrete(h.start = 90) + 
    theme_bw() 

enter image description here

+1

偉大的工作,感謝您的解決方案! – lukeg