妙用 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...