優れた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 でプログラミング

Passons à la pratique !

dplyr でプログラミング

Preparing Video For Download...