分面绘图空间

ggplot2 数据可视化进阶

Rick Scavetta

Founder, Scavetta Academy

分面与可变绘图空间

不使用一致绘图空间的原因:

变量类型 子集包含
连续型 范围差异很大
分类型 分组不同
ggplot2 数据可视化进阶

调整绘图空间...

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

ggplot2 数据可视化进阶

……但与固定坐标不兼容

ggplot(msleep2, aes(bodywt_log,
                         brainwt_log)) +
  geom_point(alpha = 0.6, shape = 16) +
  coord_fixed() +
  facet_grid(rows = vars(vore), 
             cols = vars(conservation),
             scales = "free_x")
Error: coord_fixed doesn't support free scales
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_x") 

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_y") 

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(x = bodywt_log, 
                    y = name)) +
  geom_point() +
  facet_grid(rows = vars(vore))

ggplot2 数据可视化进阶

调整绘图空间

ggplot(msleep2, aes(x = bodywt_log, 
                    y = name)) +
  geom_point() +
  # 释放 y 轴的刻度与空间
  facet_grid(rows = vars(vore), 
             scales = "free_y")

ggplot2 数据可视化进阶

调整绘图空间

ggplot(msleep2, aes(x = bodywt_log, 
                    y = name)) +
  geom_point() +
  # 释放 y 轴的刻度与空间
  facet_grid(rows = vars(vore),
             scales = "free_y", 
             space = "free_y")

ggplot2 数据可视化进阶

最后调整

msleep2 <- msleep2 %>% 
  # 按重量从高到低排序
  arrange(-bodywt_log) %>% 
  # 按顺序重设因子水平
  mutate(name = as_factor(name)) 

# 新顺序反映在 y 轴
ggplot(msleep2, aes(x = bodywt_log,
                    y = name)) +
  geom_point() +
  # 释放 y 轴的刻度与空间
  facet_grid(rows = vars(vore),
             scales = "free_y", 
             space = "free_y")

ggplot2 数据可视化进阶

Passons à la pratique !

ggplot2 数据可视化进阶

Preparing Video For Download...