はじめに

辞書の説明

概要

  • データの可視化と細かい部分の微調整をするための備忘録
  • 気になる用語や関数についてctrl + Fで検索
  • グラフ全般にかかわる共通の書式は散布図のところに多く記述
    • 散布図(1):タイトルと軸、散布図(2):凡例の調整など

参考情報

chunkの全体設定

  • fig.widthfig.heightでhtml上での図の大きさ一括指定
    • デフォルトは7
# 全体 
knitr::opts_chunk$set(echo = TRUE, warning = FALSE, message = FALSE,
                      fig.width = 5, fig.height = 4)

1 散布図(1): 2変数のみ

1.1 デフォルトの図

  • R for Data Scienceにならって、mpgデータを使用
  • mpgデータ
    • 車の人気モデル38種類における燃料効率データ(1999-2008年)
  • 使用変数の説明
    • displ: エンジンの排気量(リットル)
    • hwy: 燃料効率(miles per gallon[mpg])
library(tidyverse)
p <- 
ggplot(mpg, aes(x = displ, y = hwy))

p + geom_point() 

1.2 点の書式

1.2.1

p +
  geom_point(color = "deepskyblue3") 

1.2.2 大きさ

1.5

p +
  geom_point(size = 1.5) 

3

p +
  geom_point(size = 3) 

5

p +
  geom_point(size = 5) 

1.2.3 濃さ(透明度)

0.1

p +
  geom_point(alpha = 0.1) 

0.5

p +
  geom_point(alpha = 0.5) 

0.7

p +
  geom_point(alpha = 0.7) 

1.2.4

  • 他の形はvignette("ggplot2-specs")のshapeを参考
    • ■:“square”
    • ♦:“diamond”
    • △:“triangle open”
    • ×:“cross”
p +
  geom_point(shape = "triangle") 

1.2.5 画像: ggimage

p +
  ggimage::geom_image(aes(image = "image/kujira.PNG"))

1.3 タイトル: labs()

1.3.1 タイトルの見ばえ

p +
  geom_point() +
  labs(
    title = "タイトル",
    subtitle = "サブタイトル",
    caption = "キャプション(短い説明文)"
       )

文字サイズ変更

p +
  geom_point() +
  labs(
    title = "タイトル",
    subtitle = "サブタイトル",
    caption = "キャプション(短い説明文)"
       ) +
  theme(
    plot.title    = element_text(size = 30),
    plot.subtitle = element_text(size = 20),
    plot.caption  = element_text(size = 15)
  )

太字にして色を変更

p +
  geom_point() +
  labs(
    title = "タイトル") +
  theme(
    plot.title    = element_text(size = 30,
                                 face = "bold",      # 太字
                                 color = "darkblue") # 色
  )

位置変更

p +
  geom_point() +
  labs(
    title = "タイトル",
    subtitle = "サブタイトル",
    caption = "キャプション(短い説明文)"
       ) +
  theme(
    plot.title    = element_text(hjust = 0.5),   # 水平方向0-1の範囲で相対的な位置を指定
    plot.subtitle    = element_text(hjust = 0.5),
    plot.caption  = element_text(hjust = 0)
  )

1.3.2 フォント

  • 以下はwindowsでのやり方を想定

1.3.2.1 確認

windowsFonts()
## $serif
## [1] "TT Times New Roman"
## 
## $sans
## [1] "TT Arial"
## 
## $mono
## [1] "TT Courier New"

1.3.2.2 フォント例

Times New Roman
p +
  geom_point() +
  labs(title = "Title タイトル たいとる 題名") +
  theme(plot.title = element_text(family = "serif",
                                  size = 20))

Arial
p +
  geom_point() +
  labs(title = "Title タイトル たいとる 題名") +
  theme(plot.title = element_text(family = "sans",
                                  size = 20))

Courier New
p +
  geom_point() +
  labs(title = "Title タイトル たいとる 題名") +
  theme(plot.title = element_text(family = "mono",
                                  size = 20))

MS明朝
windowsFonts("mincho" = windowsFont("MS Mincho"))

p +
  geom_point() +
  labs(title = "Title タイトル たいとる 題名") +
  theme(plot.title = element_text(family = "mincho",
                                  size = 20))

MSゴシック
windowsFonts("gothic" = windowsFont("MS Goshic"))

p +
  geom_point() +
  labs(title = "Title タイトル たいとる 題名") +
  theme(plot.title = element_text(family = "gothic",
                                  size = 20))

メイリオ
windowsFonts("MEI" = windowsFont("Meiryo"))

p +
  geom_point() +
  labs(title = "Title タイトル たいとる 題名") +
  theme(plot.title = element_text(family = "MEI",
                                  size = 20))

游ゴシック
windowsFonts("YuGothic" = windowsFont("Yu Gothic"))

p +
  geom_point() +
  labs(title = "Title タイトル たいとる 題名") +
  theme(plot.title = element_text(family = "YuGothic",
                                  size = 20))

游明朝
windowsFonts("YuMincho" = windowsFont("Yu Mincho"))

p +
  geom_point() +
  labs(title = "Title タイトル たいとる 題名") +
  theme(plot.title = element_text(family = "YuMincho",
                                  size = 20))

1.3.2.3 画像保存時にフォントも反映させる

  • 普通に保存するだけでは変更されない
p_yugothic <- 
p +
  geom_point() +
  labs(title = "Title タイトル たいとる 題名") +
  theme(plot.title = element_text(family = "YuGothic",
                                  size = 20))

ggsave("image/p_yugothic_failed.png")

ggsave("image/p_yugothic.png", device = grDevices::png)

1.4

1.4.1 名前

  • 名前を消したいときは x = ""のようにしてもできる
p +
  geom_point() +
  labs(
    x = "x軸の名前",
    y = "y軸の名前"
       )

1.4.2 数値の書式

p +
  geom_point() +
  labs(
    title = "Title タイトル たいとる 題名",
    x = "hwy_x軸の名前",
    y = "displ_y軸の名前"
       ) +
  theme(axis.text =  element_text(family = "serif",
                                  size = 15))

1.4.3 名前の書式

p +
  geom_point() +
  labs(
    title = "Title タイトル たいとる 題名",
    x = "hwy_x軸の名前",
    y = "displ_y軸の名前"
       ) +
  theme(axis.title =  element_text(family = "serif",
                                   size = 15))

1.4.4 数値範囲: scale_continuous()

1.4.4.1 範囲確認

mpg %>% 
  select(displ, hwy) %>% # displとhwyを選んでsummary()に渡す
  summary()
##      displ            hwy       
##  Min.   :1.600   Min.   :12.00  
##  1st Qu.:2.400   1st Qu.:18.00  
##  Median :3.300   Median :24.00  
##  Mean   :3.472   Mean   :23.44  
##  3rd Qu.:4.600   3rd Qu.:27.00  
##  Max.   :7.000   Max.   :44.00

1.4.4.2 範囲を指定して1ずつ増やす

  • 数値型の場合は、scale_x_continuous()およびscale_y_continuous()のbreaksで指定
  • 表示範囲を強制指定する場合はlimits =
p +
  geom_point() +
  scale_x_continuous(
    breaks = seq(from = 1, to = 8, by = 1), # 1から8まで1ずつ増える
    limits = c(1, 8)) +                     # 1を表示したい場合
  scale_y_continuous(
    breaks = seq(from = 10, to = 45, by = 5), # 10から45まで5ずつ増える
    limits = c(10, 45))

1.4.4.2.1 手動で指定
p +
  geom_point() +
  scale_y_continuous(
    breaks = c(15, 30, 45))       

1.4.5 軸の数値のサイズ

9

p +
  geom_point() +
  theme(axis.text = element_text(size = 9)) # 単位はpt

12

p + 
  geom_point() +
  theme(axis.text = element_text(size = 12)) # 単位はpt

16

p +
  geom_point() +
  theme(axis.text = element_text(size = 16)) # 単位はpt

1.4.6 タイトルと軸のフォント(一括)

p +
  geom_point() +
  labs(
    title = "Title タイトル たいとる 題名",
    x = "hwy_x軸の名前",
    y = "displ_y軸の名前"
       ) +
  theme(text =  element_text(family = "serif",
                                  size = 15))

1.5 グラフ中に線やテキストを追加

1.5.1 横線: geom_hline()

p + 
  geom_point() +
  geom_hline(yintercept = 30,     # 座標の位置
             linetype = "dotted", # 点線
             color = "red",       # 色
             size = 1)            # 大きさ

1.5.2 縦線:geom_vline()

p +
  geom_point() +
  geom_vline(xintercept = 5,
             linetype = "dotted",
             color = "red",
             size = 1)

1.5.3 テキスト: annotate()

p +
  geom_point() +
  annotate(geom = "text",
           x = 5, y = 35,  # テキストの中心座標位置
           label = "ここにテキスト",
           color = "blue",
           size = 10)

1.5.3.1 角度

p +
  geom_point() +
  annotate(geom = "text",
           x = 5, y = 35,  # テキストの中心座標位置
           label = "ここにテキスト",
           color = "blue",
           size = 9,
           angle = 90)

1.5.3.2 フォント

p +
  geom_point() +
  annotate(geom = "text",
           x = 5, y = 35,  # テキストの中心座標位置
           label = "text テキスト",
           size = 10,
           family = "serif")

1.5.3.3 相関係数を入れる

  • 部分的にイタリックにする場合
    • rをitalic()で囲む
    • =をテキスト内に表示する場合==と入れる
    • parse = TRUEを入れる
# 相関係数の計算
corc <- 
  cor(mpg$displ, mpg$hwy) %>% 
  round(2)
 
p +
  geom_point() +
  annotate("text",
           label = str_c("italic(r) == ", corc), # 相関係数の代入 
           parse = TRUE,
           x = 6, y = 40,
           size = 6)

1.6 グラフ外にテキストを追加

  • coord_cartesian(clip = "off")を使って、グラフの灰色背景部分をxlim =,ylim =の座標で指定した領域までに表示制限する必要がある
p +
  geom_point() +
  annotate(geom = "text",
           x = 0.5, y = 7,  # テキストの中心座標位置
           color = "blue",
           sie = 10,
           label = "テキスト") +
  coord_cartesian(xlim = c(1, 7.2),
                  ylim = c(11, 44),
                  clip = "off")

1.7 グラフ内外の自由な位置にテキストや画像を追加

  • パッケージcowplotを使用
  • x,yの値は、グラフ全体の範囲をそれぞれ0~1としている

1.7.1 テキスト

library(cowplot)

ppc <- 
p + geom_point()
 
ggdraw(ppc) + 
  draw_label("text", 
             colour = "blue", 
             size = 20,
             x = 0.1,
             y = 0.2
)

1.7.2 画像

  • magickパッケージのインストールが必要
ggdraw(ppc) + 
  draw_image("image/kujira.png", 
             x = 0.5, y = 0.6,
             width = 0.3, height = 0.3)

1.8 線のあてはめ

1.8.1 曲線

p +
  geom_point() +
  geom_smooth()

1.8.2 直線

p +
  geom_point() +
  geom_smooth(method = "lm")

1.8.2.1 標準誤差の範囲を消す

p +
  geom_point() +
  geom_smooth(method = "lm", se = FALSE)

1.9 背景の色や線のテンプレート変更

theme_bw

p + 
  geom_point() +
  theme_bw()

theme_classic

p +
  geom_point() +
  theme_classic()

theme_modern

  • 全体的に見やすくなるテンプレート
  • seeパッケージに入っている
p + 
  geom_point() +
  see::theme_modern()

1.10 ジッター入り

p +
  geom_jitter()

1.10.1 ジッターの調整

0.2 x 0.2

p +
  geom_jitter(width = 0.2, height = 0.2)

0.5 x 0.5

p +
  geom_jitter(width = 0.5, height = 0.5)

1 x 1

p +
  geom_jitter(width = 1, height = 1)

2 x 0.5

p +
  geom_jitter(width = 2, height = 0.5)

0.5 x 2

p +
  geom_jitter(width = 0.5, height = 2)

1.11 データ数によって点の大きさを変える

p +
  geom_count()

2 散布図(2): 3変数以上

2.1 カテゴリ

2.1.1

  • 使用変数の説明
    • class: 車種
pc <- 
ggplot(mpg, aes(displ, hwy,
                color = class)) # 色分けに使用する変数指定

pc + geom_point()

2.1.1.1 色を手動で指定

pc +
  geom_point() +
  scale_color_manual(values = c("red", "green", "blue", "yellow", "pink", "black", "brown"))

2.1.1.1.1 凡例の名前変更
pc +
  geom_point() +
  scale_color_manual(values = c("red", "green", "blue", "yellow", "pink", "black", "brown"),
                     labels = c("二人乗り","小型","中型","ミニバン","貨物","サブコンパクト","SUV"))

2.1.1.2 用意された色のセットを使用

  • 詳しくは?scale_color_brewer
  • ユニバーサルカラーのセット例
    • Set2 (8色まで)
    • Paired(12色まで)
    • Dark2 (8色まで)
pc +
  geom_point() +
  scale_color_brewer(palette = "Set2")

2.1.2

ggplot(mpg, aes(displ, hwy,
                shape = class)) +
  geom_point()

2.1.3 テキスト

pc +
  geom_text(aes(label = class), show.legend = FALSE) # 凡例なし

2.1.3.1 重なりをなくす

pc +
  geom_text(aes(label = class), show.legend = FALSE,
            check_overlap = TRUE ) # 凡例なし

2.1.3.2 斜めにする

pc +
  geom_text(aes(label = class), show.legend = FALSE,
            angle = 45 ) # 凡例なし

2.1.4 画像

  • ggimageパッケージを使用
  • 区分するカテゴリをcase_whenで画像の保存先に割り当てる
mpg %>% 
    mutate(drv_image =
           case_when(drv == "4" ~ "image/kujira.PNG",
                     drv == "f" ~ "image/kujira_green.PNG",
                     drv == "r" ~ "image/kujira_orange.PNG")) %>% 

ggplot(aes(displ, hwy)) +
  ggimage::geom_image(aes(image = drv_image), size = .05)

2.2 数値

2.2.1 大きさ

p + 
  geom_point(aes(size = cty)) 

2.2.2 濃さ

p + 
  geom_point(aes(alpha = cty)) 

2.2.3 大きさと濃さ

p + 
  geom_point(aes(size = cty, alpha = cty)) 

2.3 凡例の調整

2.3.1 凡例の位置

pc +
 geom_point() +
 theme(legend.position = "bottom")

2.3.2 凡例を消す

pc +
 geom_point() +
 theme(legend.position = "none")

# こちらでも同じだが,複数凡例がある場合は消したいものを選択できる
# pc +
#   geom_point() +
#   guides(color = "none" )

2.3.2.1 複数凡例がある場合に残したいものを選択する

ggplot(mpg, aes(displ, hwy,
                color = class,  size = cty)) +
  geom_point() +
  guides(color = "none")

2.3.3 凡例をグラフ中に

  • legend.position = で、x軸、y軸のそれぞれを0-1の範囲で表した相対的な位置の座標で表す
  • legend.direction = "horizontal"で、凡例を横向きに展開
pc +
 geom_point() +
 theme(legend.position = c(.70, .80),
       legend.direction = "horizontal")

2.3.3.1 凡例のボックスの背景色を透明に

pc +
 geom_point() +
 theme(legend.position = c(.70, .80),
       legend.direction = "horizontal",
       legend.background = element_blank()) 

2.3.4 凡例の行数や列数指定

pc +
 geom_point() +
 theme(legend.position = "bottom") +
 guides(color = guide_legend(nrow = 1))  

2.3.5 凡例のタイトル名変更

pc +
 geom_point() +
 guides(color = guide_legend(title = "車種"))  

# こちらでもOK
# pc +
#  geom_point() +
#   labs(color = "車種")

2.3.5.1 タイトルを消す

pc +
 geom_point() +
 guides(color = guide_legend(title = ""))

# こちらでもOK
# pc +
#  geom_point() +
#   labs(color = "")

2.3.5.2 長いタイトル名の改行

  • 改行部分に\nを入れる
pc +
 geom_point() +
 guides(color = guide_legend(title = "長い\nタイトル"))  

2.3.6 凡例の順序を逆に

pc +
 geom_point() +
 guides(color = guide_legend(reverse = TRUE))

2.3.7 凡例の順序を任意に

# class別のエンジンの排気量平均を確認して並び替え
mpg %>% 
  group_by(class) %>%
  summarise(mean_hwy = mean(hwy)) %>% 
  arrange(mean_hwy)
## # A tibble: 7 × 2
##   class      mean_hwy
##   <chr>         <dbl>
## 1 pickup         16.9
## 2 suv            18.1
## 3 minivan        22.4
## 4 2seater        24.8
## 5 midsize        27.3
## 6 subcompact     28.1
## 7 compact        28.3
pc +
 geom_point() +
  scale_color_discrete(breaks =                       # 色分けをcolorでやっているのでscale_color
                        c("pickup", "suv", "minivan", 
                          "2seater", "midsize", "subcompact", "compact"))

2.3.7.1 因子にして順序を指定する場合

  • ここでは同時に実行しているが、そもそものデータフレームで因子型で順序を指定し作成しておけばその順序が反映される
mpg %>% 
  mutate(class = fct_relevel(class,
                             "pickup", "suv", "minivan", 
                          "2seater", "midsize", "subcompact", "compact")) %>% 
ggplot(aes(displ, hwy,
                color = class)) +
  geom_point()

2.3.8 凡例の背景色を消す

pc +
 geom_point() +
  theme(legend.key = element_blank())

2.4 一部のデータを目立たせる

  • geom_point()を重ね書き
    • 目立たせる車種をfilter()で選択
pp <- 
p +
# suvのデータのみプロット
   geom_point(
     data = filter(mpg, class == "suv"),
     color = "blue",
     size = 3) +
# 通常のプロット
   geom_point()

pp

2.4.1 ラベル付け

pp +
annotate(geom = "point", x = 5.5, y = 40, colour = "blue", size = 3) + 
annotate(geom = "point", x = 5.5, y = 40) + 
annotate(geom = "text", x = 5.6, y = 40, label = "suv", hjust = "left")

2.5 変数の水準ごとにプロット: facet_wrap()

pc +
   geom_point() +
   facet_wrap(vars(class))

2.5.1 並べ方指定

  • 列数: ncol = 数字
  • 行数: nrow = 数字
pc +
   geom_point() +
   facet_wrap(vars(class),
             ncol = 2)

2.5.2 ファセットラベル

2.5.2.1 文字サイズ変更

6
pc +
   geom_point() +
   facet_wrap(vars(class)) +
  theme(strip.text = element_text(size = 6))

8
pc +
   geom_point() +
   facet_wrap(vars(class)) +
  theme(strip.text = element_text(size = 8))

10
pc +
   geom_point() +
   facet_wrap(vars(class)) +
  theme(strip.text = element_text(size = 10))

2.5.2.2 背景と線の色変更

pc +
   geom_point() +
   facet_wrap(vars(class)) +
  theme(strip.background = element_rect(colour = "black", fill = "white"))

2.5.3 グラフ外にテキストを追加

library(cowplot)

pc_wrap <- 
pc +
   geom_point() +
   facet_wrap(vars(class))

ggdraw(pc_wrap) +
  draw_label("text", x = 0.05, y = 0.95, color = "blue") +
  draw_label("text", x = 0.05, y = 0.65, color = "blue") +
  draw_label("text", x = 0.05, y = 0.35, color = "blue")

2.6 変数の水準ごとにプロット(全体のプロットも残す)

  • gghilightパッケージを使う(ここだけで使うのでgghilight::をつける)
pc +
   geom_point() +
   gghighlight::gghighlight() +
   facet_wrap(vars(class))

2.7 変数の水準ごとにプロット(2要因)

pc +
   geom_point() +
   facet_wrap(vars(class,cyl))

2.7.1 変数の水準ごとにプロット(2要因):facet_grid()

pc +
   geom_point() +
   facet_grid(vars(cyl),vars(class))

3 散布図行列

3.1 GGally::ggpairs()

3.1.1 数値変数のみ

mpg |> 
  select(where(is.numeric)) |> # 数値変数だけに
  GGally::ggpairs()

3.1.1.1 背景のテンプレ変更

mpg |> 
  select(drv, where(is.numeric)) |>
  GGally::ggpairs() +
  theme_bw()

3.1.2 カテゴリも含む

mpg |> 
  select(drv, where(is.numeric)) |>
  GGally::ggpairs()

3.1.3 層別に

mpg |> 
  select(drv, where(is.numeric)) |>
  GGally::ggpairs(aes(color = drv))

4 折れ線グラフ:geom_line()

4.1 ある平均値の年次推移をグループ別にプロットしたい場合

4.1.1 必要な形のデータを作成

library(knitr) # kable()を使うため

# 車種(class)と年次別の燃料効率(hwy)平均値データを作成
hwy_class_y <- 
mpg %>% 
  group_by(class, year) %>% 
  summarise(mean_hwy = mean(hwy))

kable(hwy_class_y)
class year mean_hwy
2seater 1999 24.50000
2seater 2008 25.00000
compact 1999 27.92000
compact 2008 28.72727
midsize 1999 26.50000
midsize 2008 28.04762
minivan 1999 22.50000
minivan 2008 22.20000
pickup 1999 16.81250
pickup 2008 16.94118
subcompact 1999 29.00000
subcompact 2008 27.12500
suv 1999 17.55172
suv 2008 18.63636

4.1.1.1 (参考)wideからlongへのデータ構造変換

4.1.1.1.1 参考のためにwide型作成
hwy_class_y_w <-
  hwy_class_y %>% 
  pivot_wider(names_from = year,
              values_from = mean_hwy)

kable(hwy_class_y_w)
class 1999 2008
2seater 24.50000 25.00000
compact 27.92000 28.72727
midsize 26.50000 28.04762
minivan 22.50000 22.20000
pickup 16.81250 16.94118
subcompact 29.00000 27.12500
suv 17.55172 18.63636
  • このようなデータ(wide型)があったらlong型に変換する
4.1.1.1.2 long型に
hwy_class_y_w %>% 
  pivot_longer(-class,            # この変数以外、つまり1999と2008の列を使用
               names_to = "year",
               values_to = "mean_hwy")
## # A tibble: 14 × 3
## # Groups:   class [7]
##    class      year  mean_hwy
##    <chr>      <chr>    <dbl>
##  1 2seater    1999      24.5
##  2 2seater    2008      25  
##  3 compact    1999      27.9
##  4 compact    2008      28.7
##  5 midsize    1999      26.5
##  6 midsize    2008      28.0
##  7 minivan    1999      22.5
##  8 minivan    2008      22.2
##  9 pickup     1999      16.8
## 10 pickup     2008      16.9
## 11 subcompact 1999      29  
## 12 subcompact 2008      27.1
## 13 suv        1999      17.6
## 14 suv        2008      18.6

4.1.2 作図

ggplot(hwy_class_y, 
       aes(year, mean_hwy, color = class)) +
  geom_line()

4.1.2.1 使用した年のみのx軸の表示にしデータ点を追加する

ggplot(hwy_class_y, 
       aes(year, mean_hwy, color = class)) +
  geom_point() +
  geom_line() +
  scale_x_continuous(breaks = c(1999, 2008))

4.2 日付の軸表示

R for Data Science 24 Model building > 24.3 What affects the number of daily flights? より

4.2.1 グラフ用のデータ作成(日別の便数作成と曜日の変数追加)

library(nycflights13) # 
library(lubridate)    # 

# 日別の便数  
daily <- flights %>% 
    mutate(date = make_date(year, month, day)) %>% 
    group_by(date) %>% 
    summarise(n = n())

head(daily)  
## # A tibble: 6 × 2
##   date           n
##   <date>     <int>
## 1 2013-01-01   842
## 2 2013-01-02   943
## 3 2013-01-03   914
## 4 2013-01-04   915
## 5 2013-01-05   720
## 6 2013-01-06   832
# 曜日変数追加  
daily <- daily %>% 
    mutate(wday = wday(date, label = TRUE))    

4.2.1.1 土曜日のデータに限定

ds <- 
daily %>% 
    filter(wday == "土") %>% 
 ggplot(aes(date, n)) +
    geom_line()

ds

4.2.2 ラベルの表示調整

月ごと

  • ※ %bで数字のみが出てくる問題については、いずれ検討(おそらくlocaleの問題)
ds +
  scale_x_date(date_breaks = "1 month", date_labels = "%b") # 本来はJanなどの月名の省略文字 

半年ごと

ds +
  scale_x_date(date_breaks = "6 month", date_labels = "%Y/%b") # 西暦/月

5 ヒストグラム

ggplot(mpg) + 
  geom_histogram(aes(hwy))

5.1 分割の数

bins = 20

ggplot(mpg) + 
  geom_histogram(aes(hwy), bins = 20)

bins = 10

ggplot(mpg) + 
  geom_histogram(aes(hwy), bins = 10)

bins = 5

ggplot(mpg) + 
  geom_histogram(aes(hwy), bins = 5)

5.2 カテゴリ変数の水準ごと

ggplot(mpg) + 
  geom_histogram(aes(hwy)) + 
  facet_grid(vars(class))

6 箱ひげ図

ggplot(mpg) +
  geom_boxplot(aes(x = class, y = hwy, color = class), fill = NA)

6.1 平均値もプロット

ggplot(mpg, aes(x = class, y = hwy, color = class)) +
  geom_boxplot( fill = NA) +
  stat_summary(fun = "mean", geom = "point", shape = 23, size = 3, fill = "white")

6.2 個別の値も表示

6.2.1 jitter

  • 個別の値を示す場合は, outlier.shape = NAで外れ値表示を解除する
ggplot(mpg, aes(x = class, y = hwy, color = class)) +
  geom_boxplot( fill = NA, outlier.shape = NA) +
  geom_jitter(width = 0.2, alpha = 0.2)

6.2.2 ビースウォーム(蜂峰図、蜂群図)

  • ggbeeswarmパッケージを使う(ここだけで使うのでggbeeswarm::をつける)
ggplot(mpg, aes(x = class, y = hwy, color = class)) +
  geom_boxplot(fill = NA, outlier.shape = NA) +
  ggbeeswarm::geom_beeswarm(alpha = 0.2)

7 バイオリンプロット

7.1 デフォルトの図

ggplot(mpg, aes(x = class, y = hwy, color = class)) +
  geom_violin(aes(fill = class))  # 色分けに指定する変数

7.1.1 濃さ(透明度)

ggplot(mpg, aes(x = class, y = hwy, color = class)) +
 geom_violin(aes(fill = class),
                  alpha = 0.5)

8 ハーフバイオリン・ハーフドットプロット

8.1 デフォルトの図

  • seeパッケージのgeom_violindot()を使う
  • ドットサイズのデフォルトが0.7なのでここだけ大きくした
ggplot(mpg, aes(x = class, y = hwy, color = class)) +
  see::geom_violindot(aes(fill = class),
                     size_dots = 5) # ドットサイズ変更

9 棒グラフ(要約値から作る):geom_col()

# 【再掲】車種(class)と年次別の燃料効率(hwy)平均値データを作成
hwy_class_y <- 
mpg %>% 
  group_by(class, year) %>% 
  summarise(mean_hwy = mean(hwy))

9.1 デフォルトの図

hwy_class_y_99 <- 
hwy_class_y %>% 
  filter(year == 1999)

pb <- 
   ggplot(hwy_class_y_99, 
          aes(x = class, y = mean_hwy))

pb  + geom_col()

9.2 棒の書式

9.2.1

  • 棒グラフの場合、塗りの色はfill =で指定
pb  + geom_col(fill = "deepskyblue3")

9.2.1.1 棒ごとに色をつける

pb  + geom_col(aes(fill = class))

9.2.1.2 枠線の色

  • color =だと枠線の色に
pb  + geom_col(color = "yellow")

9.2.2 パターン

library(ggpattern)

pb +
  geom_col_pattern(
    aes(pattern = class, pattern_angle = class, pattern_spacing = class),
    fill            = 'white',
    colour          = 'black',
    pattern_spacing = 0.025,
    # pattern_density = 0.4,
    # pattern_fill    = 'black',
    # pattern_colour  = 'black'
  )

9.2.3

  • デフォルトは0.9
pb  + geom_col(width = 0.5)

9.3 x軸

9.3.1 x軸の順番を任意に

hwy_class_y_99 %>% 
  ggplot(aes(
         fct_relevel(class,
                         "pickup", "suv", "minivan", 
                        "2seater", "midsize", "subcompact", "compact"), 
             mean_hwy)) +
  geom_col() +
  labs(x = "class") 

9.3.2 降順に並び替え

  • 左から降順にしたい場合は、fct_reorder(class, mean_hwy, .desc = TRUE)
 ggplot(hwy_class_y_99, 
          aes(x = fct_reorder(class, mean_hwy), 
              y = mean_hwy)) +
  geom_col()

9.3.3 軸のラベルの角度を

  • 斜めにする
pb  + 
  geom_col() +
  theme(axis.text.x = element_text(angle = 45, 
                                   hjust = 1))

9.4 値ラベル

9.4.1 値ラベルを表示

pb + 
  geom_col() +
  geom_text(aes(label = mean_hwy))

9.4.1.1 値ラベルを表示(見た目を整える)

pb + 
  geom_col() +
  geom_text(aes(label = round(mean_hwy, 1)), # 値ラベルを丸める
            vjust = -1,                      # 値をグラフの上に表示
            size = 3.5) +                    # 値の文字のサイズ
  scale_y_continuous(limits = c(0, 30))      # y軸の範囲を指定しないとラベルが隠れるため

9.4.1.2 値を棒の中に

  • vjust =の値を大きくするほど下の位置に移動する
pb + 
  geom_col() +
  geom_text(aes(label = round(mean_hwy, 1)), # 値ラベルを丸める
            vjust = 1.5,                     # 値をグラフの中に表示
            size = 4,                        # 文字のサイズ        
            color = "white")                 # 文字の色

9.5 グラフ中に線やテキストを追加

9.5.1 縦線:geom_vline()

  • 軸がカテゴリの場合は、左から1ずつ数える
    • ここでは、5を指定しているので5本目の部分に線が引かれている
pb + 
  geom_col() +
  geom_vline(xintercept = 5,
             linetype = "dotted",
             color = "red",
             size = 1)

9.5.2 テキスト: annotate()

pb + 
  geom_col() +
  annotate(geom = "text",
           x = 4.5, y = 28,  # テキストの中心座標位置
           label = "ここにテキスト",
           color = "blue",
           size = 7)

9.6 横向きに

pb  + 
  geom_col() +
  coord_flip()

9.6.1 横向きのグラフ外にテキスト追加

pb  + 
  geom_col() +
  annotate(geom = "text",
           x = 7.5, y = -5,  # テキストの中心座標位置,表示されるグラフの見かけはXYが入れ替わる
           color = "blue",
           size = 6,
           label = "テキスト") +
   coord_flip(xlim = c(1, 7.2),
                  ylim = c(0, 30),
                  clip = "off")

10 棒グラフ(2要因以上;要約値から)

  • 折れ線グラフの時と同一データを使用
    • yearの限定なし

10.1 デフォルトの図

pby <- 
   ggplot(hwy_class_y, 
          aes(x = class, y = mean_hwy, fill = factor(year)))

pby + 
  geom_col(position = "dodge") +
  labs(fill = "year")             # 凡例のタイトル名をyearに戻す 

10.2 色を手動で指定

pby + 
  geom_col(position = "dodge") +
  scale_fill_manual(values = c("violetred3", "deepskyblue3"))

10.3 値ラベル

10.3.1 値ラベルを表示

pby + 
  geom_col(position = "dodge") +
  geom_text(aes(label = round(mean_hwy, 1)), 
            vjust = -1,
            position = position_dodge(width = 0.9), # ラベルを棒ごとに表示させる
            size = 3.5) +
  scale_y_continuous(limits = c(0, 30))

11 棒グラフ(カウントや割合):geom_bar()

11.1 デフォルトの図

pbar <- 
ggplot(mpg, aes(x = class))

pbar +  geom_bar()

11.1.1 ラベルを付ける

pbar +
  geom_bar() +
  geom_text(aes(label = ..count..), 
            stat = "count", 
            vjust = 1.5,
            color = "white") # 棒の上に黒い文字で出したい場合はこれを削除し、vjustを0.5に

11.2 カテゴリ変数1つだけで1本の棒グラフ

  • 1変数だけの場合は、x = factor(1)と固定する
  • 円グラフ参照
ggplot(mpg, 
       aes(x = factor(1), fill = class)) + 
  geom_bar() +
  labs(x = "class") +
  geom_text(aes(label = ..count..), 
            stat = "count",
            position = position_stack(vjust = 0.5)) +
  theme(axis.text.x = element_blank())                # 軸の1を消す

11.3 カテゴリ変数1つだけで1本の棒グラフ(割合)

# まずパーセントのデータを別途作成
percent <-
  mpg %>%
  count(class) %>%
  mutate(pct = scales::percent_format(accuracy = 0.1)(n/sum(n)))

# グラフ
ggplot(mpg, aes(x = factor(1), fill = factor(class))) +
  geom_bar(position = "fill") +
  geom_text(data = percent,  # 上で作ったパーセントのデータ指定
            aes(y = n, label = pct),
            position = position_fill(vjust = 0.5)) +
    scale_y_continuous(labels = scales::label_percent(accuracy = 0.1)) +   # y軸を%表記に
    theme(axis.text.x = element_blank()) +           # x軸の1を消す
  labs(x = "class")                                  # x軸の名前をclassに

11.4 2要因でカウント

  • drv:ドライブトレインのタイプ
    • f = 前輪駆動, r = 後輪駆動, 4 = 四輪駆動
pbar +
  geom_bar(aes(fill = drv))

11.4.1 ラベルを付ける

pbar +
  geom_bar(aes(fill = factor(drv))) +
  geom_text(aes(fill = factor(drv),
                label = ..count..), 
                stat = "count",
            position = position_stack(vjust = 0.5))

11.4.2 x軸の要因の水準ごとに割合として表示

pbar +
  geom_bar(aes(fill = drv),
           position = "fill") +
    scale_y_continuous(labels = scales::label_percent(accuracy = 0.1)) # 縦軸を%表記に

11.4.2.1 パーセントを表示

# まずグラフ上に表示するテキストラベルのためにパーセントのデータを別途作成
df_pct <-
  mpg %>%
  group_by(class) %>%
  count(class, drv) %>%
  mutate(pct_num = n/sum(n),
         pct = scales::percent_format(accuracy = 0.1)(pct_num))

# old
# scales::percent(pct_num)

# グラフ
ggplot(mpg, aes(x = factor(class), fill = factor(drv))) +
  geom_bar(position = "fill") +
  geom_text(data = df_pct,  # 上で作ったパーセントのデータ指定
            aes(y = n, label = pct),
            position = position_fill(vjust = 0.5)) +
    scale_y_continuous(labels = scales::label_percent(accuracy = 0.1)) # 縦軸を%表記に

11.4.3 積み上げではなく並べる

pbar +
  geom_bar(aes(fill = drv), position = "dodge")

11.4.3.1 棒の間に隙間を作る

pbar +
  geom_bar(aes(fill = drv), position = "dodge2")

11.4.3.2 水準が少ない場合も棒が太くならないようにする

  • 細かい設定を行っていく場合は、position_dodge()の中で指定していく
pbar +
  geom_bar(aes(fill = drv), 
           position = position_dodge(preserve = "single"))

11.4.3.2.1 棒の位置を真ん中にして棒の間を広げる
  • 棒の間を広げる設定はposition_dodge2()
pbar +
  geom_bar(aes(fill = drv), 
           position = position_dodge2(preserve = "single",
                                      pad = 0.3))

12 円グラフ

12.1 count

ggplot(mpg, 
       aes(x = factor(1), fill = class)) + 
  geom_bar() +
  coord_polar(theta = "y")

12.1.1 色変更

ユニバーサルカラー

ggplot(mpg, 
       aes(x = factor(1), fill = class)) + 
  geom_bar() +
  scale_fill_brewer(palette = "Set2") +
  coord_polar(theta = "y")

背景なし

ggplot(mpg, 
       aes(x = factor(1), fill = class)) + 
  geom_bar() +
  scale_fill_brewer(palette = "Set2") +
  coord_polar(theta = "y") +
  theme_classic()

12.2 割合

ggplot(mpg, aes(x = factor(1), fill = factor(class))) +
  geom_bar(position = "fill") +
  coord_polar(theta = "y")

13 ドーナツチャート

  • ggpubr::ggdonutchart

13.1 基本

# パーセント(%の前の部分の数字)のデータを別途作成
percent <-
  mpg %>%
  count(class) %>%
  mutate(pct = n/sum(n)*100,
         pctp = scales::percent_format(accuracy = 0.1)(n/sum(n))) # %付きの値も作成


ggpubr::ggdonutchart(percent, "pct", label = "class",
      fill = "class", 
      color = "white", # 区分線の色 
      lab.pos = "in", 
      lab.font = c(3, "white")) + # ラベルの文字サイズ、色
    scale_fill_brewer(palette = "Set2")

13.2 (※修正中)パーセント表示付き

14 モザイクプロット

  • 因子型の変数が必要

14.1 1変数

library(ggmosaic)

mpg %>% 
  mutate(cyl = factor(cyl)) %>% # 変数を因子型に
ggplot() +
  geom_mosaic(aes(x = product(cyl),
                  fill = cyl))

14.2 2変数

mpg %>% 
  mutate(drv = factor(drv),
         class = factor(class)) %>% # 変数を因子型に
ggplot() +
  geom_mosaic(aes(x = product(drv,class),
                  fill = drv))

15 複数のグラフを1枚にまとめる

15.1 gridExtra

15.1.1 一行または一列

p1 <- p + geom_point() 
p2 <-
  pc + 
  geom_point() +
   theme(legend.text = element_text(size = 6),# 凡例のテキストを小さく
         legend.position = "bottom",          # 凡例を下に
         legend.background = element_blank()) # 凡例のボックス背景を透明に
  
 
gridExtra::grid.arrange(p1, p2, nrow = 1) # 1行に

gridExtra::grid.arrange(p1, p2, ncol = 1) # 1列に

15.1.2 四等分(2x2)

p3 <- 
pc +
   geom_point() +
   facet_wrap(vars(class)) +
 theme(legend.position = "none") # 凡例を消す

gridExtra::grid.arrange(p1, p2, p3, ncol = 2) # 2列に

15.2 patchwork

library(patchwork)

p1 + p2

(p1 | p2)/p3

16

16.1 ユニバーサルカラー

library(RColorBrewer)
display.brewer.all(colorblindFriendly= TRUE)

16.2 色を増やす

# デフォルトではPairedは12色のみ
many_col <- brewer.pal(12, "Paired")
many_col
##  [1] "#A6CEE3" "#1F78B4" "#B2DF8A" "#33A02C" "#FB9A99" "#E31A1C" "#FDBF6F"
##  [8] "#FF7F00" "#CAB2D6" "#6A3D9A" "#FFFF99" "#B15928"
# 20色まで増やす
many_col <- colorRampPalette(many_col)(20)
many_col
##  [1] "#A6CEE3" "#579CC7" "#3688AD" "#8BC395" "#89CB6C" "#40A635" "#919D5F"
##  [8] "#F99392" "#EB494A" "#E83C2D" "#F79C5D" "#FDA746" "#FE8205" "#E39970"
## [15] "#BFA5CF" "#8861AC" "#917099" "#E7E099" "#DEB969" "#B15928"
pie(rep(1, length(many_col)), col = many_col, main = "")