Một mẹo hay với ggplot

Lập trình với dplyr

Dr. Chester Ismay

Educator, Data Scientist, and R/Python Consultant

Cơ bản về ggplot2

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

geom_histogram(color = "white")

Biểu đồ tần suất của infant_mortality_rate

Lập trình với dplyr

Thêm tiêu đề

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

ggtitle("A histogram of infant_mortality_rate")

ggplot2 với tiêu đề

Lập trình với dplyr

Gói vào một hàm

# Mã vẽ trước đó
ggplot(world_bank_data, aes(x = infant_mortality_rate)) + 
  geom_histogram(color = "white") +
  ggtitle("A histogram of infant_mortality_rate")
# Định nghĩa hàm
my_histogram <- function(

df, x_var) {
ggplot(df, aes(x = x_var)) + geom_histogram(color = "white") + ggtitle(paste("A histogram of", x_var)) }
Lập trình với dplyr

Hoàn thiện hàm của chúng ta

# Lần thử đầu viết hàm
my_histogram <- function(df, x_var) {
  ggplot(df, aes(x = x_var)) +
    geom_histogram(color = "white") +
    ggtitle(paste("A histogram of", x_var))
}

# Gọi hàm 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
Lập trình với dplyr

Thêm rlang vào

# Lần thử đầu viết hàm
my_histogram <- function(df, x_var) {
  ggplot(df, aes(x = x_var)) +
    geom_histogram(color = "white") +
    ggtitle(paste("A histogram of", x_var))
}
# Chỉnh sửa cần thiết để tránh lỗi
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))) }
Lập trình với dplyr

Dùng hàm của chúng ta

# Định nghĩa hàm với toán tử 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))
    ))
}

# Gọi hàm với pipe! world_bank_data %>% my_histogram(x_var = perc_rural_pop)

Biểu đồ tần suất ggplot2 với rlang

Lập trình với dplyr

Ayo berlatih!

Lập trình với dplyr

Preparing Video For Download...