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 中的广义线性模型

因子转数值

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 中的广义线性模型

Passons à la pratique !

R 中的广义线性模型

Preparing Video For Download...