漂亮的 ggplot 小巧思

使用 dplyr 進行程式設計

Dr. Chester Ismay

Educator, Data Scientist, and R/Python Consultant

ggplot2 基礎

library(ggplot2)
ggplot(
    world_bank_data, 
    aes(x = infant_mortality_rate)
) +

geom_histogram(color = "white")

infant_mortality_rate 的直方圖

使用 dplyr 進行程式設計

加入標題

ggplot(
    world_bank_data, 
    aes(x = infant_mortality_rate)
) + 
  geom_histogram(color = "white") +

ggtitle("A histogram of infant_mortality_rate")

含標題的 ggplot2

使用 dplyr 進行程式設計

封裝成函式

# 先前的作圖程式碼
ggplot(world_bank_data, aes(x = infant_mortality_rate)) + 
  geom_histogram(color = "white") +
  ggtitle("A histogram of infant_mortality_rate")
# 定義函式
my_histogram <- function(

df, x_var) {
ggplot(df, aes(x = x_var)) + geom_histogram(color = "white") + ggtitle(paste("A histogram of", x_var)) }
使用 dplyr 進行程式設計

改進我們的函式

# 函式的第一次嘗試
my_histogram <- function(df, x_var) {
  ggplot(df, aes(x = x_var)) +
    geom_histogram(color = "white") +
    ggtitle(paste("A histogram of", x_var))
}

# 呼叫函式 my_histogram(df = world_bank_data, x_var = infant_mortality_rate)
 Error in paste("A histogram of", x_var) : 
  object 'infant_mortality_rate' not found
使用 dplyr 進行程式設計

加入 rlang

# 函式的第一次嘗試
my_histogram <- function(df, x_var) {
  ggplot(df, aes(x = x_var)) +
    geom_histogram(color = "white") +
    ggtitle(paste("A histogram of", x_var))
}
# 做必要的調整以避免錯誤
my_histogram <- function(df, x_var) {
  ggplot(df, aes(x = {{ x_var }})) +

geom_histogram(color = "white") + ggtitle(paste("A histogram of",
as_label(enquo(x_var))) }
使用 dplyr 進行程式設計

使用我們的函式

# 使用 rlang 運算子的已定義函式
my_histogram <- function(df, x_var) {
  ggplot(df, aes(x = {{ x_var }})) +
    geom_histogram(color = "white") +
    ggtitle(paste(
      "A histogram of", 
      as_label(enquo(x_var))
    ))
}

# 用管線呼叫函式! world_bank_data %>% my_histogram(x_var = perc_rural_pop)

使用 rlang 的 ggplot2 直方圖

使用 dplyr 進行程式設計

一起來練習吧!

使用 dplyr 進行程式設計

Preparing Video For Download...