ggplot2 與二元 GLM

R 的廣義線性模型

Richard Erickson

Instructor

我能從資料看見什麼?

通勤距離會影響搭公車的機率嗎?

ggplot(bus, aes(x = MilesOneWay, y = Bus)) + geom_point()

只有點的圖

R 的廣義線性模型

geom_jitter()

gg_jitter <- ggplot(bus, aes(x = MilesOneWay, y = Bus)) +
             geom_jitter(width = 0, height = 0.05)
print(gg_jitter) 

抖動散點圖

R 的廣義線性模型

geom_smooth()

gg_jitter + geom_smooth()

在先前抖動圖上加入平滑曲線。

R 的廣義線性模型

factor 轉數值

str(bus)
bus$Bus2 <- as.numeric(bus$Bus) - 1 
R 的廣義線性模型

geom_smooth()

gg_jitter + geom_smooth() 

將資料改為數值而非字元

R 的廣義線性模型

線性模型

gg_jitter + geom_smooth(method = 'glm')

在 ggJitter 上加入 lm

R 的廣義線性模型

羅吉斯迴歸

ggJitter + 
geom_smooth(method = 'glm',
            method.args = list(family = "binomial")) 

ggJitter 加上羅吉斯曲線

R 的廣義線性模型
gg_jitter + 
    geom_smooth(method = 'glm',
                method.args = list(family = binomial(link = 'logit')),
                se = FALSE, color = 'red') +
    geom_smooth(method = 'glm',
                method.args = list(family = binomial(link = 'probit')),
                se = FALSE, color = 'blue') 

ggJitter 同時含 logit 與 probit 圖

R 的廣義線性模型

步驟總結

  • 用抖動圖避免重疊
  • 加上平滑幾何
  • 指定正確的 method 與 family
  • 美化圖形(本課未涵蓋)
R 的廣義線性模型

一起來練習吧!

R 的廣義線性模型

Preparing Video For Download...