facet_wrap 与边际图

ggplot2 数据可视化进阶

Rick Scavetta

Founder, Scavetta Academy

调整绘图区间距

ggplot(msleep2, aes(bodywt_log, 
                    brainwt_log)) +
  geom_point(alpha = 0.6, shape = 16) +
  facet_grid(rows = vars(vore), 
             cols = vars(conservation),
             scales = "free") 

ggplot2 数据可视化进阶

使用 facet_wrap()

适用场景:

  1. 需要在每个小图中同时放开 x 与 y 轴范围
    • 即不按 facet_grid() 的行或列分别放开
ggplot2 数据可视化进阶

使用 facet_wrap() - 情景 1

ggplot(msleep2, aes(bodywt_log, 
                    brainwt_log)) +
  geom_point(alpha = 0.6, shape = 16) +
  facet_wrap(vars(vore, conservation),
             scales = "free") 

ggplot2 数据可视化进阶

使用 facet_wrap()

适用场景:

  1. 需要在每个小图中同时放开 x 与 y 轴范围
    • 即不按 facet_grid() 的行或列分别放开
  2. 分类型(因子)变量分组很多(水平多)
    • 即按行/列分面会产生过多子图
    • 更常见的情形
ggplot2 数据可视化进阶

使用 facet_wrap() - 情景 2

ggplot(msleep2, aes(bodywt_log, 
                    brainwt_log)) +
  geom_point(alpha = 0.6, shape = 16) +
  facet_wrap(vars(order))

ggplot2 数据可视化进阶

使用边际图

ggplot(msleep2, aes(bodywt_log, 
                    brainwt_log)) +
  geom_point(alpha = 0.6, shape = 16) +
  facet_grid(rows = vars(vore), 
             cols = vars(conservation),
             scales = "free") 

ggplot2 数据可视化进阶

使用边际图

ggplot(msleep2, aes(bodywt_log, 
                    brainwt_log)) +
  geom_point(alpha = 0.6, shape = 16) +
  facet_grid(rows = vars(vore), 
             cols = vars(conservation),
             scales = "free",
             margins = TRUE) 

ggplot2 数据可视化进阶

使用边际图

ggplot(msleep2, aes(bodywt_log, 
                    brainwt_log)) +
  geom_point(alpha = 0.6, shape = 16) +
  facet_grid(rows = vars(vore), 
             cols = vars(conservation),
             scales = "free",
             margins = "conservation")

ggplot2 数据可视化进阶

Passons à la pratique !

ggplot2 数据可视化进阶

Preparing Video For Download...