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. 分類(factor)變數的群組(層級)很多
    • 也就是列或欄分面會產生過多小圖
    • 更常見的情境
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 中級資料視覺化

一起來練習吧!

ggplot2 中級資料視覺化

Preparing Video For Download...