分面繪圖空間

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 中級資料視覺化

一起來練習吧!

ggplot2 中級資料視覺化

Preparing Video For Download...