Categories: R

R 使用 ggplot2 繪製箱形圖 Box Plot 教學與範例

介紹如何在 R 中使用 ggplot2 套件繪製各種樣式的箱型圖(box plot)。

測試資料

安裝並載入 ggplot2 套件:

# 安裝 ggplot2 套件
install.packages("ggplot2")

# 載入 ggplot2 套件
library(ggplot2)

這裡我們以 ToothGrowth 資料集為範例,此資料集包含三欄變數:

# 顯示 ToothGrowth 的資料結構
str(ToothGrowth)
'data.frame':   60 obs. of  3 variables:
 $ len : num  4.2 11.5 7.3 5.8 6.4 10 11.2 11.2 5.2 7 ...
 $ supp: Factor w/ 2 levels "OJ","VC": 2 2 2 2 2 2 2 2 2 2 ...
 $ dose: num  0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 ...

單一變數箱形圖

如果要使用 ggplot 繪製單一變數的箱形圖,可加上 scale_x_discrete 將 X 軸標示移除。例如將 ToothGrowth 資料集中的 len 資料分布繪製成箱形圖:

# 單一變數箱形圖
ggplot(ToothGrowth, aes(y = len)) +
  geom_boxplot() +     # 箱形圖
  scale_x_discrete() + # 移除 X 軸標示
  ylab("Length")       # Y 軸標示文字
單一變數箱形圖

若要將目前以 ggplot2 所繪製的圖形儲存起來,可以使用 ggsave 函數:

# 儲存 ggplot2 目前繪製的圖形
ggsave("output.png", width = 3, height = 3)

分組箱形圖

依據 dose 的數值分組,繪製基本的箱形圖:

# 繪製基本箱形圖
ggplot(ToothGrowth, aes(x = as.factor(dose), y = len)) +
  geom_boxplot() + # 箱形圖
  xlab("Dose") +   # X 軸標示文字
  ylab("Length")   # Y 軸標示文字
分組箱形圖

這裡的 dose 實際上是數值資料,若要當成類別型的資料來作為分組的依據,就要先以 as.factor 將其轉為因子(factor)變數,這樣 ggplot 才會畫出正確的圖。

加入標題文字

透過 labs 可以加入標題、副標題等說明文字:

# 加入標題、描述等文字
ggplot(ToothGrowth, aes(x = as.factor(dose), y = len)) +
  geom_boxplot() +
  xlab("Dose") +
  ylab("Length") +
  labs(title = "測試箱形圖", subtitle = "這是描述文字") +
  labs(caption = "資料來源:https://officeguide.cc/")
加入標題文字

X 軸與 Y 軸互換

加入 coord_flip 可以讓 ggplot 圖形的 X 軸與 Y 軸互換:

# X 軸與 Y 軸互換
ggplot(ToothGrowth, aes(x = as.factor(dose), y = len)) +
  geom_boxplot() +
  xlab("Dose") +
  ylab("Length") +
  coord_flip()     # X 軸與 Y 軸互換
X 軸與 Y 軸互換

缺口箱形圖

geom_boxplot 中加入 notch 參數,可以繪製缺口箱形圖,缺口範圍代表中位數的 95% 信賴區間:

# 繪製缺口箱形圖
ggplot(ToothGrowth, aes(x = as.factor(dose), y = len)) +
  geom_boxplot(notch = TRUE) + # 缺口箱形圖
  xlab("Dose") +
  ylab("Length")
缺口箱形圖

自訂離群值標示

離群值(outlier)標示點的顏色、大小與樣式都可以自訂:

# 自訂離群值標示
ggplot(ToothGrowth, aes(x = as.factor(dose), y = len)) +
  geom_boxplot(outlier.colour = "red", # 離群值標示顏色
               outlier.shape = 4,      # 離群值標示樣式
               outlier.size = 4) +     # 離群值標示大小
  xlab("Dose") +
  ylab("Length")
自訂離群值標示

僅顯示指定組別

透過 scale_x_discrete 可以指定要繪製箱形圖的組別,將不重要的組別隱藏起來:

# 僅顯示指定組別
ggplot(ToothGrowth, aes(x = as.factor(dose), y = len)) +
  geom_boxplot() +
  xlab("Dose") +
  ylab("Length") +
  scale_x_discrete(limits = c("0.5", "2")) # 僅顯示 0.5 與 2
僅顯示指定組別

加入資料點

geom_dotplot 可以將實際的資料位置以點的方式標示在箱形圖中:

# 加入資料點
ggplot(ToothGrowth, aes(x = as.factor(dose), y = len)) +
  geom_boxplot() +
  xlab("Dose") +
  ylab("Length") +
  geom_dotplot(binaxis = 'y',       # 加入資料點
               stackdir = 'center', # 置中對齊
               dotsize = 0.8)       # 資料點大小
加入資料點

加入錯開位置的資料點

geom_jitter 可以加入錯開位置的資料點,避免資料點重疊問題:

# 加入錯開位置的資料點
ggplot(ToothGrowth, aes(x = as.factor(dose), y = len)) +
  geom_boxplot() +
  xlab("Dose") +
  ylab("Length") +
  geom_jitter(shape = 16,                      # 資料點樣式
              position = position_jitter(0.2)) # 資料點位置
加入錯開位置的資料點

依組別上色

若要將不同組別的資料以不同顏色表示,可以使用 color 參數指定上色的依據:

# 依據 dose 上色
ggplot(ToothGrowth, aes(x = as.factor(dose), y = len, color = as.factor(dose))) +
  geom_boxplot() +
  xlab("Dose") +
  ylab("Length") +
  labs(color = "Dose") # 圖示區標題
依組別上色

自訂色彩

亦可使用 scale_color_manual 以色碼自行指定色彩:

# 以預設色彩繪圖
p <- ggplot(ToothGrowth, aes(x = as.factor(dose), y = len, color = as.factor(dose))) +
  geom_boxplot() +
  xlab("Dose") +
  ylab("Length") +
  labs(color = "Dose")

# 自訂色彩
p + scale_color_manual(values = c("#999999", "#E69F00", "#56B4E9"))
自訂色彩

採用 brewer 色盤

採用內建的 brewer 色盤來挑選顏色:

# 採用 brewer 色盤
p + scale_color_brewer(palette = "Dark2")
採用 brewer 色盤

灰階配色

使用灰階配色:

# 灰階配色
p + scale_color_grey() + theme_classic()
灰階配色

依據組別填滿顏色

若要依據組別設定填滿顏色,可以使用 fill 參數指定上色的依據:

# 依據 dose 填滿顏色
ggplot(ToothGrowth, aes(x = as.factor(dose), y = len, fill = as.factor(dose))) +
  geom_boxplot() +
  xlab("Dose") +
  ylab("Length") +
  labs(fill = "Dose") # 圖示區標題
依據組別填滿顏色

自訂填滿色彩

亦可使用 scale_fill_manual 以色碼自行指定填滿的色彩:

# 以預設色彩繪圖
p <- ggplot(ToothGrowth, aes(x = as.factor(dose), y = len, fill = as.factor(dose))) +
  geom_boxplot() +
  xlab("Dose") +
  ylab("Length") +
  labs(fill = "Dose")

# 自訂色彩
p + scale_fill_manual(values = c("#999999", "#E69F00", "#56B4E9"))
自訂填滿色彩

採用 brewer 色盤

採用內建的 brewer 色盤來挑選填滿顏色:

# 採用 brewer 色盤
p + scale_fill_brewer(palette = "Dark2")
採用 brewer 色盤

灰階配色

使用灰階配色:

# 灰階配色
p + scale_fill_grey() + theme_classic()
灰階配色

更改圖示說明位置

使用 themelegend.position 參數可以更改圖示說明位置,例如將圖示放在上方:

# 更改圖示說明位置(上方)
p + theme(legend.position = "top")

更改圖示說明位置(上方)

將圖示放在下方:

# 更改圖示說明位置(下方)
p + theme(legend.position = "bottom")

更改圖示說明位置(下方)

亦可自行指定圖示說明位置:

# 更改圖示說明位置(自訂位置)
p + theme(legend.position = c(0.85, 0.25))
更改圖示說明位置(自訂位置)

移除圖示說明

若將 themelegend.position 參數設定為 none 則可移除圖示說明:

# 移除圖示說明
p + theme(legend.position = "none")
移除圖示說明

二次分組

若需要依據第二種類別進行二次分組,可以將 fill 指定為第二種類別:

# 依據 supp 二次分組
ggplot(ToothGrowth, aes(x = as.factor(dose), y = len, fill = supp)) +
  geom_boxplot(position = position_dodge(1))
二次分組

參考資料

Share
Published by
Office Guide
Tags: ggplot2

Recent Posts

Python 使用 PyAutoGUI 自動操作滑鼠與鍵盤

本篇介紹如何在 Python ...

9 個月 ago

Ubuntu Linux 以 WireGuard 架設 VPN 伺服器教學與範例

本篇介紹如何在 Ubuntu ...

9 個月 ago

Linux 網路設定 ip 指令用法教學與範例

本篇介紹如何在 Linux 系...

10 個月 ago

Windows 使用 TPM 虛擬智慧卡保護 SSH 金鑰教學與範例

本篇介紹如何在 Windows...

11 個月 ago

Linux 以 Shamir’s Secret Sharing 分割保存金鑰教學與範例

介紹如何在 Linux 中使用...

11 個月 ago

Linux 以 Cryptsetup、LUKS 加密 USB 隨身碟教學與範例

介紹如何在 Linux 系統中...

11 個月 ago