ggplot2 数据可视化进阶
Rick Scavetta
Founder, Scavetta Academy
不使用一致绘图空间的原因:
| 变量类型 | 子集包含 |
|---|---|
| 连续型 | 范围差异很大 |
| 分类型 | 分组不同 |
ggplot(msleep2, aes(bodywt_log,
brainwt_log)) +
geom_point(alpha = 0.6, shape = 16) +
coord_fixed() +
facet_grid(rows = vars(vore),
cols = vars(conservation))

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

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

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

ggplot(msleep2, aes(x = bodywt_log,
y = name)) +
geom_point() +
facet_grid(rows = vars(vore))

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

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

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 数据可视化进阶