はじめに
辞書の説明
概要
- データの可視化と細かい部分の微調整をするための備忘録
- 気になる用語や関数についてctrl + Fで検索
- グラフ全般にかかわる共通の書式は散布図のところに多く記述
- 散布図(1):タイトルと軸、散布図(2):凡例の調整など
 
 
chunkの全体設定
- fig.widthと- fig.heightでhtml上での図の大きさ一括指定
# 全体 
knitr::opts_chunk$set(echo = TRUE, warning = FALSE, message = FALSE,
                      fig.width = 5, fig.height = 4)
 
 
 
 散布図(1):
2変数のみ
 デフォルトの図
- 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() 

 
 点の書式
 色
p +
  geom_point(color = "deepskyblue3") 

 
大きさ
1.5
p +
  geom_point(size = 1.5) 

 
3
p +
  geom_point(size = 3) 

 
5
p +
  geom_point(size = 5) 

 
 
濃さ(透明度)
0.1
p +
  geom_point(alpha = 0.1) 

 
0.5
p +
  geom_point(alpha = 0.5) 

 
0.7
p +
  geom_point(alpha = 0.7) 

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

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

 
 
 タイトル: labs()
タイトルの見ばえ
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)
  )

 
 
 フォント
 確認
windowsFonts()
## $serif
## [1] "TT Times New Roman"
## 
## $sans
## [1] "TT Arial"
## 
## $mono
## [1] "TT Courier New"
 
フォント例
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))

 
 
画像保存時にフォントも反映させる
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)

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

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

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

 
 数値範囲:
scale_continuous()
 範囲確認
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ずつ増やす
- 数値型の場合は、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))

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

 
 
 
軸の数値のサイズ
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

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

 
 軸の名前を消す
p +
  geom_point() +
  theme(axis.title = element_blank())

# こちらでもできる
# p +
#   geom_point() +
#   labs(x = "",
#        y = "")
 
軸の数値と線を消す
p +
  geom_point() +
  theme(axis.text = element_blank(),
        axis.ticks = element_blank())

 
 
グラフ中に線やテキストを追加
 横線:
geom_hline()
p + 
  geom_point() +
  geom_hline(yintercept = 30,     # 座標の位置
             linetype = "dotted", # 点線
             color = "red",       # 色
             size = 1)            # 大きさ

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

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

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

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

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

 
相関係数を入れる
- 部分的にイタリックにする場合
- 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)

 
 
 
グラフ外にテキストを追加
- 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")

 
グラフ内外の自由な位置にテキストや画像を追加
- パッケージcowplotを使用
- x,yの値は、グラフ全体の範囲をそれぞれ0~1としている
 テキスト
library(cowplot)
ppc <- 
p + geom_point()
 
ggdraw(ppc) + 
  draw_label("text", 
             colour = "blue", 
             size = 20,
             x = 0.1,
             y = 0.2
)

 
 画像
ggdraw(ppc) + 
  draw_image("image/kujira.png", 
             x = 0.5, y = 0.6,
             width = 0.3, height = 0.3)

 
 
 線のあてはめ
 曲線
p +
  geom_point() +
  geom_smooth()

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

標準誤差の範囲を消す
p +
  geom_point() +
  geom_smooth(method = "lm", se = FALSE)

 
 
 
背景の色や線のテンプレート変更
theme_bw
p + 
  geom_point() +
  theme_bw()

 
theme_classic
p +
  geom_point() +
  theme_classic()

 
theme_void
p +
  geom_point() +
  theme_void()

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

 
 
 ジッター入り
p +
  geom_jitter()

ジッターの調整
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)

 
 
 
データ数によって点の大きさを変える
p +
  geom_count()

 
 
 散布図(2):
3変数以上
 カテゴリ
 色
pc <- 
ggplot(mpg, aes(displ, hwy,
                color = class)) # 色分けに使用する変数指定
pc + geom_point()

色を手動で指定
pc +
  geom_point() +
  scale_color_manual(values = c("red", "green", "blue", "yellow", "pink", "black", "brown"))

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

 
 
用意された色のセットを使用
- 詳しくは?scale_color_brewer
- ユニバーサルカラーのセット例
- Set2 (8色まで)
- Paired(12色まで)
- Dark2 (8色まで)
 
pc +
  geom_point() +
  scale_color_brewer(palette = "Set2")

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

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

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

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

 
 
 画像
- 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)

 
 
 数値
 大きさ
p + 
  geom_point(aes(size = cty)) 

 
 濃さ
p + 
  geom_point(aes(alpha = cty)) 

 
 大きさと濃さ
p + 
  geom_point(aes(size = cty, alpha = cty)) 

 
 
 凡例の調整
 凡例の位置
pc +
 geom_point() +
 theme(legend.position = "bottom")

 
 凡例を消す
pc +
 geom_point() +
 theme(legend.position = "none")

# こちらでも同じだが,複数凡例がある場合は消したいものを選択できる
# pc +
#   geom_point() +
#   guides(color = "none" )
複数凡例がある場合に残したいものを選択する
ggplot(mpg, aes(displ, hwy,
                color = class,  size = cty)) +
  geom_point() +
  guides(color = "none")

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

凡例のボックスの背景色を透明に
pc +
 geom_point() +
 theme(legend.position = c(.70, .80),
       legend.direction = "horizontal",
       legend.background = element_blank()) 

 
 
凡例の行数や列数指定
pc +
 geom_point() +
 theme(legend.position = "bottom") +
 guides(color = guide_legend(nrow = 1))  

 
凡例のタイトル名変更
pc +
 geom_point() +
 guides(color = guide_legend(title = "車種"))  

# こちらでもOK
# pc +
#  geom_point() +
#   labs(color = "車種")
タイトルを消す
pc +
 geom_point() +
 guides(color = guide_legend(title = ""))

# こちらでもOK
# pc +
#  geom_point() +
#   labs(color = "")
 
長いタイトル名の改行
pc +
 geom_point() +
 guides(color = guide_legend(title = "長い\nタイトル"))  

 
 
凡例の順序を逆に
pc +
 geom_point() +
 guides(color = guide_legend(reverse = TRUE))

 
凡例の順序を任意に
# 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"))

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

 
 
凡例の背景色を消す
pc +
 geom_point() +
  theme(legend.key = element_blank())

 
 
一部のデータを目立たせる
pp <- 
p +
# suvのデータのみプロット
   geom_point(
     data = filter(mpg, class == "suv"),
     color = "blue",
     size = 3) +
# 通常のプロット
   geom_point()
pp

 ラベル付け
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")

 
 
変数の水準ごとにプロット: facet_wrap()
pc +
   geom_point() +
   facet_wrap(vars(class))

 並べ方指定
- 列数: ncol = 数字
- 行数: nrow = 数字
pc +
   geom_point() +
   facet_wrap(vars(class),
             ncol = 2)

 
ファセットラベル
文字サイズ変更
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))

 
 
背景と線の色変更
pc +
   geom_point() +
   facet_wrap(vars(class)) +
  theme(strip.background = element_rect(colour = "black", fill = "white"))

 
 
グラフ外にテキストを追加
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")

 
 
変数の水準ごとにプロット(全体のプロットも残す)
- gghilightパッケージを使う(ここだけで使うので- gghilight::をつける)
pc +
   geom_point() +
   gghighlight::gghighlight() +
   facet_wrap(vars(class))

 
変数の水準ごとにプロット(2要因)
pc +
   geom_point() +
   facet_wrap(vars(class,cyl))

変数の水準ごとにプロット(2要因):facet_grid()
pc +
   geom_point() +
   facet_grid(vars(cyl),vars(class))

 
 
 
 散布図行列
GGally::ggpairs()
 数値変数のみ
mpg |> 
  select(where(is.numeric)) |> # 数値変数だけに
  GGally::ggpairs()

背景のテンプレ変更
mpg |> 
  select(drv, where(is.numeric)) |>
  GGally::ggpairs() +
  theme_bw()

 
 
 カテゴリも含む
mpg |> 
  select(drv, where(is.numeric)) |>
  GGally::ggpairs()

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

 
 
 
折れ線グラフ:geom_line()
ある平均値の年次推移をグループ別にプロットしたい場合
必要な形のデータを作成
library(knitr) # kable()を使うため
# 車種(class)と年次別の燃料効率(hwy)平均値データを作成
hwy_class_y <- 
mpg %>% 
  group_by(class, year) %>% 
  summarise(mean_hwy = mean(hwy))
kable(hwy_class_y)
| 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 | 
(参考)wideからlongへのデータ構造変換
参考のためにwide型作成
hwy_class_y_w <-
  hwy_class_y %>% 
  pivot_wider(names_from = year,
              values_from = mean_hwy)
kable(hwy_class_y_w)
| 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型に変換する
 
 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
 
 
 
 作図
ggplot(hwy_class_y, 
       aes(year, mean_hwy, color = class)) +
  geom_line()

使用した年のみのx軸の表示にしデータ点を追加する
ggplot(hwy_class_y, 
       aes(year, mean_hwy, color = class)) +
  geom_point() +
  geom_line() +
  scale_x_continuous(breaks = c(1999, 2008))

 
 
 
 日付の軸表示
R for Data Science 24
Model building > 24.3 What affects the number of daily flights?
より
グラフ用のデータ作成(日別の便数作成と曜日の変数追加)
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))    
土曜日のデータに限定
ds <- 
daily %>% 
    filter(wday == "土") %>% 
 ggplot(aes(date, n)) +
    geom_line()
ds

 
 
ラベルの表示調整
- date_labels =の後に指定する文字の意味は- ?strptimeを参照
- 教科書ggplot2: Elegant Graphics for Data Analysisでは
月ごと
- ※
%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") # 西暦/月

 
 
 
 
 ヒストグラム
ggplot(mpg) + 
  geom_histogram(aes(hwy))

分割の数
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)

 
 
カテゴリ変数の水準ごと
ggplot(mpg) + 
  geom_histogram(aes(hwy)) + 
  facet_grid(vars(class))

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

 平均値もプロット
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")

 
 個別の値も表示
 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)

 
ビースウォーム(蜂峰図、蜂群図)
- ggbeeswarmパッケージを使う(ここだけで使うので- ggbeeswarm::をつける)
ggplot(mpg, aes(x = class, y = hwy, color = class)) +
  geom_boxplot(fill = NA, outlier.shape = NA) +
  ggbeeswarm::geom_beeswarm(alpha = 0.2)

 
 
 
 バイオリンプロット
 デフォルトの図
ggplot(mpg, aes(x = class, y = hwy, color = class)) +
  geom_violin(aes(fill = class))  # 色分けに指定する変数

 濃さ(透明度)
ggplot(mpg, aes(x = class, y = hwy, color = class)) +
 geom_violin(aes(fill = class),
                  alpha = 0.5)

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

 
 
棒グラフ(要約値から作る):geom_col()
# 【再掲】車種(class)と年次別の燃料効率(hwy)平均値データを作成
hwy_class_y <- 
mpg %>% 
  group_by(class, year) %>% 
  summarise(mean_hwy = mean(hwy))
 デフォルトの図
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()

 
 棒の書式
 色
pb  + geom_col(fill = "deepskyblue3")

棒ごとに色をつける
pb  + geom_col(aes(fill = class))

 
 枠線の色
pb  + geom_col(color = "yellow")

 
 
 パターン
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'
  )

 
 幅
pb  + geom_col(width = 0.5)

 
 
 x軸
x軸の順番を任意に
hwy_class_y_99 %>% 
  ggplot(aes(
         fct_relevel(class,
                         "pickup", "suv", "minivan", 
                        "2seater", "midsize", "subcompact", "compact"), 
             mean_hwy)) +
  geom_col() +
  labs(x = "class") 

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

 
軸のラベルの角度を
pb  + 
  geom_col() +
  theme(axis.text.x = element_text(angle = 45, 
                                   hjust = 1))

 
 
 値ラベル
 値ラベルを表示
pb + 
  geom_col() +
  geom_text(aes(label = mean_hwy))

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

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

 
 
 
グラフ中に線やテキストを追加
縦線:geom_vline()
- 軸がカテゴリの場合は、左から1ずつ数える
- ここでは、5を指定しているので5本目の部分に線が引かれている
 
pb + 
  geom_col() +
  geom_vline(xintercept = 5,
             linetype = "dotted",
             color = "red",
             size = 1)

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

 
 
 横向きに
pb  + 
  geom_col() +
  coord_flip()

横向きのグラフ外にテキスト追加
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")

 
 
 
棒グラフ(2要因以上;要約値から)
 デフォルトの図
pby <- 
   ggplot(hwy_class_y, 
          aes(x = class, y = mean_hwy, fill = factor(year)))
pby + 
  geom_col(position = "dodge") +
  labs(fill = "year")             # 凡例のタイトル名をyearに戻す 

 
 色を手動で指定
pby + 
  geom_col(position = "dodge") +
  scale_fill_manual(values = c("violetred3", "deepskyblue3"))

 
 値ラベル
値ラベルを表示
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))

 
 
 
棒グラフ(カウントや割合):geom_bar()
 デフォルトの図
pbar <- 
ggplot(mpg, aes(x = class))
pbar +  geom_bar()

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

 
 
カテゴリ変数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を消す

 
カテゴリ変数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に

 
 2要因でカウント
- drv:ドライブトレインのタイプ- 
- f = 前輪駆動, r = 後輪駆動, 4 = 四輪駆動
 
pbar +
  geom_bar(aes(fill = drv))

ラベルを付ける
pbar +
  geom_bar(aes(fill = factor(drv))) +
  geom_text(aes(fill = factor(drv),
                label = ..count..), 
                stat = "count",
            position = position_stack(vjust = 0.5))

 
x軸の要因の水準ごとに割合として表示
pbar +
  geom_bar(aes(fill = drv),
           position = "fill") +
    scale_y_continuous(labels = scales::label_percent(accuracy = 0.1)) # 縦軸を%表記に

パーセントを表示
- 小数点第1位まで表示させるためにaccuracy = 0.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)) # 縦軸を%表記に

 
 
積み上げではなく並べる
pbar +
  geom_bar(aes(fill = drv), position = "dodge")

棒の間に隙間を作る
pbar +
  geom_bar(aes(fill = drv), position = "dodge2")

 
水準が少ない場合も棒が太くならないようにする
- 細かい設定を行っていく場合は、position_dodge()の中で指定していく
pbar +
  geom_bar(aes(fill = drv), 
           position = position_dodge(preserve = "single"))

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

 
 
 
 
 
 円グラフ
 count
ggplot(mpg, 
       aes(x = factor(1), fill = class)) + 
  geom_bar() +
  coord_polar(theta = "y")

色変更
ユニバーサルカラー
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()

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

 
 
 ドーナツチャート
 基本
# パーセント(%の前の部分の数字)のデータを別途作成
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")

 
(※修正中)パーセント表示付き
 
 モザイクプロット
 1変数
library(ggmosaic)
mpg %>% 
  mutate(cyl = factor(cyl)) %>% # 変数を因子型に
ggplot() +
  geom_mosaic(aes(x = product(cyl),
                  fill = cyl))

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

 
 
複数のグラフを1枚にまとめる
 patchwork
library(patchwork)
p1 + p2

(p1 | p2)/p3

 
 
 色
ユニバーサルカラー
library(RColorBrewer)
display.brewer.all(colorblindFriendly= TRUE)

 
 色を増やす
# デフォルトでは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 = "")
