主題的彈性

ggplot2 資料視覺化入門

Rick Scavetta

Founder, Scavetta Academy

使用主題的方式

  1. 從零開始(上一支影片)
ggplot2 資料視覺化入門

使用主題的方式

  1. 從零開始(上一支影片)
  2. 主題圖層物件
  3. 內建主題
    • ggplot2 或 ggthemes 套件
  4. 其他套件的內建主題
  5. 更新/設定預設主題
ggplot2 資料視覺化入門

定義主題物件

  • 當有許多圖時很實用
  • 風格一致
  • 全域套用特定主題
ggplot2 資料視覺化入門

定義主題物件

z <- ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) + 
  geom_jitter(alpha = 0.6) +
  scale_x_continuous("Sepal Length (cm)", limits = c(4,8), expand = c(0,0)) +
  scale_y_continuous("Sepal Width (cm)", limits = c(1.5,5), expand = c(0,0)) +
  scale_color_brewer("Species", palette = "Dark2", labels = c("Setosa", "Versicolor", "Virginica"))

ggplot2 資料視覺化入門

定義主題物件

z + theme(text = element_text(family = "serif", size = 14),
          rect = element_blank(),
          panel.grid = element_blank(),
          title = element_text(color = "#8b0000"),
          axis.line = element_line(color = "black"))

ggplot2 資料視覺化入門

定義主題物件

theme_iris <- theme(text = element_text(family = "serif", size = 14),
          rect = element_blank(),
          panel.grid = element_blank(),
          title = element_text(color = "#8b0000"),
          axis.line = element_line(color = "black"))
ggplot2 資料視覺化入門

重複使用主題物件

z + theme_iris

ggplot2 資料視覺化入門

重複使用主題物件

m <- ggplot(iris, aes(x = Sepal.Width)) + 
    geom_histogram(binwidth = 0.1,
                   center = 0.05)
m                 

ggplot2 資料視覺化入門

重複使用主題物件

m +
  theme_iris

ggplot2 資料視覺化入門

重複使用主題物件

m + 
  theme_iris +
  theme(axis.line.x = element_blank())

ggplot2 資料視覺化入門

使用主題的方式

  1. 從零開始(上一支影片)
  2. 主題圖層物件
  3. 內建主題
    • ggplot2 或 ggthemes 套件
  4. 其他套件的內建主題
  5. 更新/設定預設主題
ggplot2 資料視覺化入門

使用內建主題

使用 theme_*() 函式存取內建主題。

z + 
  theme_classic()

ggplot2 資料視覺化入門

使用內建主題

使用 theme_*() 函式存取內建主題。

z + 
  theme_classic() +
  theme(text = element_text(family = "serif"))

ggplot2 資料視覺化入門

使用主題的方式

  1. 從零開始(上一支影片)
  2. 主題圖層物件
  3. 內建主題
    • ggplot2 或 ggthemes 套件
  4. 其他套件的內建主題
  5. 更新/設定預設主題
ggplot2 資料視覺化入門

ggthemes 套件

使用 ggthemes 套件可取得更多函式。

library(ggthemes)
z + 
  theme_tufte()

ggplot2 資料視覺化入門

使用主題的方式

  1. 從零開始(上一支影片)
  2. 主題圖層物件
  3. 內建主題
    • ggplot2 或 ggthemes 套件
  4. 其他套件的內建主題
  5. 更新/設定預設主題
ggplot2 資料視覺化入門

更新主題

original <- theme_update(text = element_text(family = "serif", size = 14),
                         rect = element_blank(),
                         panel.grid = element_blank(),
                         title = element_text(color = "#8b0000"),
                         axis.line = element_line(color = "black"))
ggplot2 資料視覺化入門

更新主題

z

ggplot2 資料視覺化入門

設定主題

theme_set(original)

# Alternatively
# theme_set(theme_grey())

ggplot2 資料視覺化入門

一起來練習吧!

ggplot2 資料視覺化入門

Preparing Video For Download...