class: center, middle, inverse, title-slide # R Club - Lesson 4 ##
http://s.opur.club/18d4
### Kenji Sato ### 2018/11/21 & 28 --- $$\let\oldhat\hat \renewcommand{\hat}[1]{\oldhat{\hspace{0pt} #1}}$$ <div style="margin-top: -2.5em"></div> ## Cheat Sheets <https://www.rstudio.com/resources/cheatsheets/> R の主要なパッケージの主要な関数がコンパクトにまとめられていて大変便利。 本日は,「Data Visualization Cheat Sheet」の内容をざっと確認する。 --- ## トピック - ggplot2 による可視化の入門 - gpplot2 を使って PWT データの可視化 - ついでに乱数を生成する関数を学ぶ。 --- ## tidyverse - R プロジェクトを開く - Data フォルダに PWT データ - Graphics フォルダがあることを確認 - **tidyverse** をロードする ```r # 自宅でやる場合は,install.packages("tidyverse") を実行 library(tidyverse) ``` --- ## Review: ggplot2 の基本構造 ```r ggplot(dataframe) + geom_*(aes(...)) + geom_*(aes(...), data = 他のデータ) + # geom_* は必要な数だけ <その他装飾のためのレイヤー> ``` 保存するには,プロットした後に ```r ggsave("Graphics/filename.pdf") ``` などとする。 --- ## データ生成 ```r set.seed(611) N <- 100 group <- factor(sample(c("Good", "Normal", "Bad"), size = N, replace = TRUE), levels = c("Good", "Normal", "Bad")) x <- rnorm(N) y <- 0.8 * x + runif(N) + 0.4 * as.integer(group) df <- tibble(xval = x, yval = y, group) head(df) ``` ``` ## # A tibble: 6 x 3 ## xval yval group ## <dbl> <dbl> <fct> ## 1 0.945 1.46 Good ## 2 -0.176 1.44 Normal ## 3 1.31 2.95 Bad ## 4 2.46 3.67 Normal ## 5 -0.111 1.58 Normal ## 6 0.0663 1.48 Bad ``` --- ## 各グループの数:棒グラフ 次のグラフを作成してください。 <img src="slides_files/figure-html/geom_bar-1.png" height="400" style="display: block; margin: auto;" /> --- ## 各グループの数:棒グラフ ```r ggplot(df) + geom_bar(aes(x = group)) ``` `count` はどこにも書いていないけど計算されている。これは `geom_bar()` を呼び出したときに自動的に計算される「デフォルトの `stat`」だから。 明示的に書けば次のようになる。 ```r ggplot(df) + geom_bar(aes(x = group), stat = "count") ``` --- ## 座標の反転 ```r ggplot(df) + geom_bar(aes(x = group)) + * coord_flip() ``` <img src="slides_files/figure-html/geom_bar_flip-1.png" height="400" style="display: block; margin: auto;" /> --- ## 各グループの割合:棒グラフ カウントでなく割合をプロットしたい場合にはどうする? <img src="slides_files/figure-html/fraction-1.png" height="400" style="display: block; margin: auto;" /> --- ## 各グループの割合:棒グラフ `..count..` で内部的に計算されているカウントデータを利用できる。 ```r ggplot(df) + geom_bar(aes(x = group, y = ..count.. / sum(..count..))) ``` 2つのドットで囲んだ `..statname..` は内部的に計算された集計情報を利用するための方法。ときどき使われることがあるので,覚えておいてください。 もちろん **dplyr** で下処理をしてもよい。 --- ## 割合:積み上げ棒グラフ 割合を示すときには,次のようなグラフを使うことが多い。 ```r df %>% group_by(_____) %>% summarize(cases = n()) %>% ggplot() + geom_col(aes(x = 1, y = _____, fill = _____)) ``` <img src="slides_files/figure-html/fraction2-1.png" height="250" style="display: block; margin: auto;" /> --- ## `geom_col` or `geom_bar`? `geom_col` は高さがデータの別の値になる。`stat = 'identity'` `geom_bar` は高さがカウントデータになる。`stat = 'count'` --- ## 割合:パイチャート ```r df %>% group_by(group) %>% summarize(cases = n()) %>% ggplot() + geom_col(aes(x = 1, y = cases, fill = group)) + _____(theta = 'y') ``` <img src="slides_files/figure-html/pie-1.png" height="250" style="display: block; margin: auto;" /> --- ## 番外編:ワッフルチャート ```r # install.packages("waffle") summary <- df %>% group_by(group) %>% summarize(cases = n()) summary.vec <- summary$cases names(summary.vec) <- summary$group waffle::waffle(summary.vec) ``` <img src="slides_files/figure-html/waffle-1.png" height="250" style="display: block; margin: auto;" /> --- ## 分布 `xval` の分布を見てみよう。 ```r df %>% ggplot(aes(x = xval)) + geom_histogram() ``` ``` ## `stat_bin()` using `bins = 30`. Pick better value with ## `binwidth`. ``` <img src="slides_files/figure-html/xdist-1.png" height="250" style="display: block; margin: auto;" /> --- ## 分布 グループごとの分布を見たい場合は?次はうまくいかない ```r df %>% ggplot(aes(x = xval, fill = group)) + geom_histogram() ``` ``` ## `stat_bin()` using `bins = 30`. Pick better value with ## `binwidth`. ``` <img src="slides_files/figure-html/badgraph-1.png" height="250" style="display: block; margin: auto;" /> --- ## `position = "dodge"` ```r df %>% ggplot(aes(x = xval, fill = group)) + geom_histogram(position = "dodge") ``` ``` ## `stat_bin()` using `bins = 30`. Pick better value with ## `binwidth`. ``` <img src="slides_files/figure-html/dodge-1.png" height="250" style="display: block; margin: auto;" /> --- ## `facet_wrap` ```r df %>% ggplot(aes(x = xval)) + geom_histogram() + facet_wrap(~ group) ``` ``` ## `stat_bin()` using `bins = 30`. Pick better value with ## `binwidth`. ``` <img src="slides_files/figure-html/facetwrap-1.png" height="300" style="display: block; margin: auto;" /> --- ## ヴァイオリンプロット ```r df %>% ggplot() + geom_violin(aes(x = group, y = xval, fill = group)) ``` <img src="slides_files/figure-html/violin-1.png" height="300" style="display: block; margin: auto;" /> --- ## 箱ひげ図 ```r df %>% ggplot() + geom_boxplot(aes(x = group, y = xval, fill = group)) + coord_flip() ``` <img src="slides_files/figure-html/boxplot-1.png" height="300" style="display: block; margin: auto;" /> --- ## 散布図 XY の関係を調べる基本は散布図。 ```r df %>% ggplot() + geom_point(aes(x = xval, y = yval)) ``` <img src="slides_files/figure-html/scatter-1.png" height="300" style="display: block; margin: auto;" /> --- ## 色づけ ```r df %>% ggplot() + geom_point(aes(x = xval, y = yval, _________)) ``` <img src="slides_files/figure-html/scatter2-1.png" height="300" style="display: block; margin: auto;" /> --- ## 比較をしやすくする工夫 ```r ggplot(df) + geom_point(data = select(df, -group), aes(x = xval, y = yval), color = "gray70") + # color は aes の外! geom_point(aes(x = xval, y = yval, color = group)) + facet_wrap(~ group) ``` <img src="slides_files/figure-html/scatter3-1.png" height="300" style="display: block; margin: auto;" /> --- ## Penn World Table PWT を使って「所得収束 = 所得が高かった国ほど遅く成長する」を確認しよう。サンプルとしてOECD加盟国(2018年11月現在)のデータに限定する。 ```r oecd <- c("Australia", "Austria", "Belgium", "Canada", "Chile", "Czech Republic", "Denmark", "Estonia", "Finland", "France", "Germany", "Greece", "Hungary", "Iceland", "Ireland", "Israel", "Italy", "Japan", "Republic of Korea", "Latvia", "Lithuania", "Luxembourg", "Mexico", "Netherlands", "New Zealand", "Norway", "Poland", "Portugal", "Slovakia", "Slovenia", "Spain", "Sweden", "Switzerland", "Turkey", "United Kingdom", "United States") ``` --- ```r pwt90 <- haven::read_dta("Data/pwt90.dta") ``` ```r pwt_oecd <- pwt90 %>% filter(year >= 1965, country %in% oecd) %>% mutate(productivity = rgdpo / (emp * avh)) %>% group_by(country) %>% summarize(avg_growth = mean((log(productivity)) - lag(log(productivity)), na.rm = TRUE), productivity_1965 = first(productivity)) %>% filter(!is.na(productivity_1965)) head(pwt_oecd) ``` ``` ## # A tibble: 6 x 3 ## country avg_growth productivity_1965 ## <chr> <dbl> <dbl> ## 1 Australia 0.0186 19.4 ## 2 Austria 0.0317 11.4 ## 3 Belgium 0.0279 14.8 ## 4 Canada 0.0165 21.7 ## 5 Chile 0.0226 8.05 ## 6 Denmark 0.0283 15.5 ``` --- ```r ggplot(pwt_oecd, aes(x = productivity_1965, y = avg_growth)) + geom_point() + labs( x = "Labor Productivity in 1965", y = "Average Growth for 1965-2014" ) ``` <img src="slides_files/figure-html/oecd1-1.png" height="400" style="display: block; margin: auto;" /> --- ```r ggplot(pwt_oecd, aes(x = productivity_1965, y = avg_growth)) + geom_point() + * scale_x_log10() + # 対数スケール labs(x = "Labor Productivity in 1965", y = "Average Growth for 1965-2014") ``` <img src="slides_files/figure-html/oecd2-1.png" height="400" style="display: block; margin: auto;" /> --- ```r ggplot(pwt_oecd, aes(x = productivity_1965, y = avg_growth)) + geom_point() + scale_x_log10() + * geom_smooth(method = lm) + # 回帰直線 labs(x = "Labor Productivity in 1965", y = "Average Growth for 1965-2014") ``` <img src="slides_files/figure-html/oecd3-1.png" height="400" style="display: block; margin: auto;" /> --- 注目したい点にラベルをつける ```r pwt_irr <- pwt_oecd %>% filter(productivity_1965 < 3 | rank(desc(productivity_1965)) < 4 | rank(desc(avg_growth)) < 4) pwt_irr ``` ``` ## # A tibble: 6 x 3 ## country avg_growth productivity_1965 ## <chr> <dbl> <dbl> ## 1 Canada 0.0165 21.7 ## 2 Ireland 0.0452 7.87 ## 3 Japan 0.0375 6.40 ## 4 Republic of Korea 0.0594 1.72 ## 5 Switzerland 0.0223 22.0 ## 6 United States 0.0168 27.8 ``` --- **ggrepel** をインストール ```r install.packages("ggrepel") library(ggrepel) ``` --- ```r ggplot(pwt_oecd, aes(x = productivity_1965, y = avg_growth)) + geom_point() + geom_smooth(method = lm, se = FALSE) + geom_label_repel(data = pwt_irr, aes(label = country), box.padding = 1.5) + scale_x_log10() + labs(x = "Labor Productivity in 1965", y = "Average Growth for 1965-2014") ``` <img src="slides_files/figure-html/repel-1.png" height="400" style="display: block; margin: auto;" /> --- ## 課題 - <https://ggplot2.tidyverse.org/reference/ggsave.html> もしまだやっていなければ,`ggsave()` を使って画像を保存してみる。 - <https://ggplot2.tidyverse.org/reference/index.html#section-themes> `theme` について勉強する。例えば,`theme_light()` を追加するとどうなるか? - <https://ggplot2.tidyverse.org/reference/index.html#section-layer-geoms> 自分の知らない `geom_*` を勉強する。どのようなケースでそれが使えるか?