멋진 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...