準備

今回使うパッケージを読み込む。pathwork パッケージをインストール済みでないなら、まずインストールする。

#install.packages("patchwork")
library(tidyverse)
library(broom)
library(patchwork)

Macユーザのみ 次のコマンドも実行する。

theme_set(theme_gray(base_size = 10, base_family = "HiraginoSans-W3"))

Windows ユーザのみ 次のコマンドも実行する。

windowsFonts(YuGothic = windowsFont("Yu Gothic"))
theme_set(theme_gray(base_size = 10, base_family = "YuGothic"))

ggplot2 パッケージを使った作図の基本は理解していることを前提に話を進める。

R に含まれているアヤメ (iris) のデータを使う。

data(iris)
glimpse(iris)
## Rows: 150
## Columns: 5
## $ Sepal.Length <dbl> 5.1, 4.9, 4.7, 4.6, 5.0, 5.4, 4.6, 5.0, 4.4, 4.9, 5.4, 4…
## $ Sepal.Width  <dbl> 3.5, 3.0, 3.2, 3.1, 3.6, 3.9, 3.4, 3.4, 2.9, 3.1, 3.7, 3…
## $ Petal.Length <dbl> 1.4, 1.4, 1.3, 1.5, 1.4, 1.7, 1.4, 1.5, 1.4, 1.5, 1.5, 1…
## $ Petal.Width  <dbl> 0.2, 0.2, 0.2, 0.2, 0.2, 0.4, 0.3, 0.2, 0.2, 0.1, 0.2, 0…
## $ Species      <fct> setosa, setosa, setosa, setosa, setosa, setosa, setosa, …

Sepal(がく片 [外花被片])の長さと幅、petal(花弁 [内花被片])の長さと幅、species(種類)の5つの変数があることがわかる。

ggplot2で作った図の微調整

ラベルの変更

まず、ヒストグラムを作る。

hist1 <- ggplot(iris, aes(x = Petal.Length, y = after_stat(density))) +
    geom_histogram(color = "black")
plot(hist1)
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

ラベルは、labs() で変更する。

hist2 <- hist1 + 
    labs(x = "花弁の長さ", 
         y = "確率密度", 
         title = "ヒストグラムの例")
plot(hist2)
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

横軸を0から10まで、縦軸を0から1までに変更する。

hist3 <- hist2 + 
    xlim(0, 10) + 
    ylim(0, 1)
plot(hist3)
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

特定の領域にフォーカスした図を作ってみよう。 例えば、\(x\in[3, 7]\) の部分のみ表示してみる。

hist4 <- hist2 + 
    coord_cartesian(xlim = c(3, 7))
plot(hist4)
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

誤ってこの方法を使うと、図の一部だけを見て間違った結論を出すおそれがあるので注意すること。

図を並べる

色分け

iris データに何種類のアヤメのデータがあるか確認する。

length(unique(iris$Species))
## [1] 3
with(iris, table(Species))
## Species
##     setosa versicolor  virginica 
##         50         50         50

3種類のアヤメがある。

種類ごとに色分けしよう。

hist5 <- ggplot(iris, aes(x = Petal.Length, y = after_stat(density),
                          fill = Species)) +
    geom_histogram(color = "black") +
    labs(x = "花弁の長さ", y = "確率密度")
plot(hist5)
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

色の組み合わせ(カラーパレット)を変える。 色分けされているのはfill なので、scale_fill_brewer() を使う。

hist6 <- hist5 +
    scale_fill_brewer(palette = "Accent")
plot(hist6)
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

凡例の調整

ラベルと色分けを説明する凡例 (legend) を日本語に変えよう。

hist6j <- hist5 +
    scale_fill_brewer(palette = "Set2",
                      name = "種類",
                      labels = c("ヒオウギアヤメ (setosa)", 
                                 "ブルーフラッグ (verisicolor)", 
                                 "バージニア (virginica)"))
plot(hist6j)
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

ggplot のfacet 機能を使って図を並べる

上のヒストグラムでは、1つの作図領域に3つの種類が一緒に描かれている。重なっている部分がよく見えないので、種類ごとに別々の作図領域にヒストグラムを描き、並べて表示しよう。facetを使うと、データをグループ別にした図ができる。

facet_wrap()

作図領域の大きさに応じて適当に複数の図を並べたいときは、facet_wrap() を使う。facet_wrap(vars(group_var)) とすると、group_var に記録されたグループごとに図を作り並べる。

hist_facet1 <- ggplot(iris, aes(x = Petal.Length, y = after_stat(density))) +
    geom_histogram(color = "black") +
    labs(x = "花弁の長さ", y = "確率密度") +
    facet_wrap(vars(Species))
plot(hist_facet1)
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

種類によって分布する範囲が異なることがわかる。図によって軸を自由に動かすには、次のようにする。

hist_facet2 <- ggplot(iris, aes(x = Petal.Length, y = after_stat(density))) +
    geom_histogram(color = "black", binwidth = 0.1) +
    labs(x = "花弁の長さ", y = "確率密度") +
    facet_wrap(vars(Species), scale = "free")
plot(hist_facet2)

x軸のみ自由にする。

hist_facet2x <- ggplot(iris, aes(x = Petal.Length, y = after_stat(density))) +
    geom_histogram(color = "black", binwidth = 0.1) +
    labs(x = "花弁の長さ", y = "確率密度") +
    facet_wrap(vars(Species), scale = "free_x")
plot(hist_facet2x)

y軸のみ自由にする。

hist_facet2y <- ggplot(iris, aes(x = Petal.Length, y = after_stat(density))) +
    geom_histogram(color = "black", binwidth = 0.1) +
    labs(x = "花弁の長さ", y = "確率密度") +
    facet_wrap(vars(Species), scale = "free_y")
plot(hist_facet2y)

グループの数がもっと多いとどうなるかを確認するために、適当なデータフレーム (tibble) を作る。

x <- NULL
n <- 1000
for (i in 1:10) {
  x <- c(x, rnorm(n, mean = i * 2, sd = i))
}
df <- tibble(x = x,
             group_var = factor(rep(1:10, each = n)))

グループ別のヒストグラムを作る。

hist_facet3 <- ggplot(df, aes(x = x, y = after_stat(density))) +
    geom_histogram(color = "black") +
    facet_wrap(vars(group_var))
plot(hist_facet3)
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

facet_grid()

行と列を指定して並べるときはfacet_grid(rows = vars(行のグループ変数), cols = vars(列のグループ変数)) を使う。

まず、アヤメの種類ごとに横に(つまり、1種類を1列にして)並べる。

hist_facet4 <- ggplot(iris, aes(x = Petal.Length, y = after_stat(density))) +
    geom_histogram(color = "black", binwidth = 0.1) +
    labs(x = "花弁の長さ", y = "確率密度") +
    facet_grid(cols = vars(Species))
plot(hist_facet4)

次に、アヤメの種類ごとに縦に(つまり、1種類を1行にして)並べる。

hist_facet5 <- ggplot(iris, aes(x = Petal.Length, y = after_stat(density))) +
    geom_histogram(color = "black") +
    labs(x = "花弁の長さ", y = "確率密度") +
    facet_grid(rows = vars(Species))
plot(hist_facet5)
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

グリッド表示は、グループ変数が2つあるときに便利である。 例として、適当なデータフレーム(tibble)を作る。

mean <- c(-2, 0, 2)
sd <- c(0.5, 1, 1.5, 2)
x <- NULL
n <- 1000
for (m in seq_along(mean)) {
  for (s in seq_along(sd))
    x <- c(x, rnorm(n, mean = m, sd = s))
}
df <- tibble(x = x,
             mean = paste0("mean=", rep(mean, each = 4 * n)),
             sd = paste0("sd=", rep(rep(sd, each = n), 3)))
hist_facet6 <- ggplot(df, aes(x = x, y = after_stat(density))) +
    geom_histogram(color = "black") +
    facet_grid(rows = vars(mean), cols = vars(sd))
plot(hist_facet6)
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

facet_wrap() を使うとどうなるだろうか。やってみよう。

hist_facet7 <- ggplot(df, aes(x = x, y = after_stat(density))) +
    geom_histogram(color = "black") +
    facet_wrap(mean ~ sd)
plot(hist_facet7)
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

patchwork パッケージ

別々に作った図を、後で並べることもできる。それを実現するのに便利なのが、patchwork パッケージである(このページ では既に読み込み済み)。patchwork で図を横に並べるときは、+ 記号で複数の図を繋ぐ。 図を縦に並べるときは、/ 記号で複数の図を繋ぐ。+/ を組み合わせて使えば、グラフの行列を作ることができる。

やってみよう。まず、種類ごとにヒストグラムを作る。

hist_setosa <- iris %>% 
    filter(Species == "setosa") %>% 
    ggplot(aes(x = Petal.Length, y = after_stat(density))) +
    geom_histogram(color = "black", 
                   fill = "darkslateblue",
                   binwidth = 0.1) +
    xlim(0, 8) + 
    ylim(0, 3) +
    labs(x = "花弁の長さ", y = "確率密度")

hist_versicolor <- iris %>% 
    filter(Species == "versicolor") %>% 
    ggplot(aes(x = Petal.Length, y = after_stat(density))) +
    geom_histogram(color = "black", 
                   fill = "blue",
                   binwidth = 0.1) +
    xlim(0, 8) + 
    ylim(0, 3) +
    labs(x = "花弁の長さ", y = "確率密度")
hist_virginica <- iris %>% 
    filter(Species == "virginica") %>% 
    ggplot(aes(x = Petal.Length, y = after_stat(density))) +
    geom_histogram(color = "black",
                   fill = "cornsilk",
                   binwidth = 0.1) +
    xlim(0, 8) + ylim(0, 3) +
    labs(x = "花弁の長さ", y = "確率密度")

横に並べる。

plot(hist_setosa + hist_versicolor + hist_virginica)

縦に並べる。

plot(hist_setosa / hist_versicolor / hist_virginica)

組み合わせて使うと、さまざまな並べ方を実現できる。例えば、次のようにできる。

plot(hist_setosa / (hist_versicolor + hist_virginica))

図の保存

Rで作った図を保存するときは、図のサイズを指定して保存すべきである。いい加減な大きさで保存し、他のアプリケーション(例えば、LibreOffice Writer など)に貼り付けてから図のサイズを変えると、図のラベルや軸目盛の文字の形が崩れて見栄えが悪くなるので、やめた方がよい。サイズは、幅 (width) と 高さ (height) で指定する。

例えば、A4用紙は幅が8.27インチ、縦が11.69 インチなので、半ページ程度の図なら width = 6, height = 4 のようにする。1ページ分の図なら、 width = 6, height = 8 程度にする(余白も考慮する)。

図で使用する文字のフォントも指定して方がよい。macOSの場合は、

theme_set(theme_gray(base_size = 10, base_family = "HiraginoSans-W3"))

とすることで、フォントサイズ10ptのヒラギノゴシック体(ウェイトは3)を指定することができる。

Windows の場合は、

windowsFonts("YuGothic" = windowsFont("Yu Gothic"))
theme_set(theme_gray(base_size = 10, base_family = "YuGothic"))

とすれば、フォントサイズ10ptの游ゴシックフォントが指定できる(はず)。

図を保存する方法は、macOS と Windows でやや異なるので注意すること。 PDFファイルを保存する方法を復習しよう。

macOS の場合

XQuartz がインストールされているMac では、quartz() で図が保存できる。 quartz()からdev.off() までが1セットである。Rmdファイル上では、quartz()からdev.off() まで一挙に実行する必要がある(図を保存するための一連の命令を1つのチャンクに書き、コードチャンク右上の “Run Current Chunk” ボタンをクリックすればよい。ショートカットは Cmd + Shift + return)。ファイル名は file で指定する。次の例では、hist_row.pdf という名前のファイルに図が保存される。

quartz(file = "hist_row.pdf", type = "pdf", family = "HiraginoSans-W3",
       width = 6, height = 4)
print(hist_setosa + hist_versicolor + hist_virginica)
dev.off()

保存した図(PDFファイル)を開き、ちゃんと保存できたか確認すること。

Windows の場合

Windowsでは、pdf() で図が保存できる。 pdf()からdev.off() までが1セットである。Rmdファイル上では、pdf()からdev.off() まで一挙に実行する必要がある(図を保存するための一連の命令を1つのチャンクに書き、コードチャンク右上の “Run Current Chunk” ボタンをクリックすればよい。ショートカットは Ctrl + Shift + Enter)。ファイル名は file で指定する。次の例では、hist_row.pdf という名前のファイルに図が保存される。

pdf(file = "hist_row.pdf", family = "YuGothic",  width = 6, height = 4)
print(hist_setosa + hist_versicolor + hist_virginica)
dev.off()

保存した図(PDFファイル)を開き、ちゃんと保存できたか確認すること



授業の内容に戻る