<base関数>
<ggplot2>
# 準備:使用するデータセット
mtcars %>% glimpse()
## Observations: 32
## Variables: 11
## $ mpg <dbl> 21.0, 21.0, 22.8, 21.4, 18.7, 18.1, 14.3, 24.4, 22.8, 19....
## $ cyl <dbl> 6, 6, 4, 6, 8, 6, 8, 4, 4, 6, 6, 8, 8, 8, 8, 8, 8, 4, 4, ...
## $ disp <dbl> 160.0, 160.0, 108.0, 258.0, 360.0, 225.0, 360.0, 146.7, 1...
## $ hp <dbl> 110, 110, 93, 110, 175, 105, 245, 62, 95, 123, 123, 180, ...
## $ drat <dbl> 3.90, 3.90, 3.85, 3.08, 3.15, 2.76, 3.21, 3.69, 3.92, 3.9...
## $ wt <dbl> 2.620, 2.875, 2.320, 3.215, 3.440, 3.460, 3.570, 3.190, 3...
## $ qsec <dbl> 16.46, 17.02, 18.61, 19.44, 17.02, 20.22, 15.84, 20.00, 2...
## $ vs <dbl> 0, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, ...
## $ am <dbl> 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, ...
## $ gear <dbl> 4, 4, 4, 3, 3, 3, 3, 4, 4, 4, 4, 3, 3, 3, 3, 3, 3, 4, 4, ...
## $ carb <dbl> 4, 4, 1, 1, 2, 1, 4, 2, 2, 4, 4, 3, 3, 3, 4, 4, 4, 1, 2, ...
# base関数による散布図
mtcars %$% plot(wt, mpg)
# ggplot2パッケージ(qplot関数)
mtcars %$% qplot(wt, mpg)
# ggplot2パッケージ(ggplot関数)
mtcars %>% ggplot(aes(wt, mpg)) + geom_point()
# 準備:使用するデータセット
pressure %>% glimpse()
## Observations: 19
## Variables: 2
## $ temperature <dbl> 0, 20, 40, 60, 80, 100, 120, 140, 160, 180, 200, 2...
## $ pressure <dbl> 0.0002, 0.0012, 0.0060, 0.0300, 0.0900, 0.2700, 0....
# base関数による折れ線グラフ
pressure %$% plot(temperature, pressure, type = "l")
# ラインチャートにポイントに丸印をつける
pressure %$% points(temperature , pressure )
# 系列を追加する
pressure %$% lines(temperature ,pressure/2 , col = "red")
pressure %$% points(temperature ,pressure/2 , col = "red" )
# 折れ線グラフのラインを引く
pressure %$% qplot(temperature, pressure, geom = "line" )
# 引数の設定で折れ線と点を両方同時に描画できる
pressure %$% qplot(temperature, pressure, geom = c("line", "point"))
# ggplot関数で描くと以下のとおり
pressure %>%
ggplot(aes(temperature , pressure)) +
geom_line() +
geom_point()
# 準備:使用するデータセット
BOD %>% glimpse()
## Observations: 6
## Variables: 2
## $ Time <dbl> 1, 2, 3, 4, 5, 7
## $ demand <dbl> 8.3, 10.3, 19.0, 16.0, 15.6, 19.8
# 数値を棒フラグ
# --- 数値をそのまま棒グラフにする
BOD %$% barplot(demand, names.arg = Time)
# 個数を棒グラフ化
# --- table関数でベクトル内でグループごとに個数を集計
mtcars$cyl %>% table() %>% barplot()
# 数値を棒フラグ(数値をそのまま棒グラフにする)
# ggplot関数で描くと以下のとおり
BOD %>%
ggplot(aes(Time, demand)) +
geom_bar(stat = "identity")
# 準備:使用するデータセット
mtcars %>% glimpse()
## Observations: 32
## Variables: 11
## $ mpg <dbl> 21.0, 21.0, 22.8, 21.4, 18.7, 18.1, 14.3, 24.4, 22.8, 19....
## $ cyl <dbl> 6, 6, 4, 6, 8, 6, 8, 4, 4, 6, 6, 8, 8, 8, 8, 8, 8, 4, 4, ...
## $ disp <dbl> 160.0, 160.0, 108.0, 258.0, 360.0, 225.0, 360.0, 146.7, 1...
## $ hp <dbl> 110, 110, 93, 110, 175, 105, 245, 62, 95, 123, 123, 180, ...
## $ drat <dbl> 3.90, 3.90, 3.85, 3.08, 3.15, 2.76, 3.21, 3.69, 3.92, 3.9...
## $ wt <dbl> 2.620, 2.875, 2.320, 3.215, 3.440, 3.460, 3.570, 3.190, 3...
## $ qsec <dbl> 16.46, 17.02, 18.61, 19.44, 17.02, 20.22, 15.84, 20.00, 2...
## $ vs <dbl> 0, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, ...
## $ am <dbl> 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, ...
## $ gear <dbl> 4, 4, 4, 3, 3, 3, 3, 4, 4, 4, 4, 3, 3, 3, 3, 3, 3, 4, 4, ...
## $ carb <dbl> 4, 4, 1, 1, 2, 1, 4, 2, 2, 4, 4, 3, 3, 3, 4, 4, 4, 1, 2, ...
# ヒストグラムを作成する
mtcars %$% hist(mpg)
# ビン(データ区間)の分割回数はbreaks引数で指定する
mtcars %$% hist(mpg, breaks = 10)
# 選択データを1つにするとヒストグラムになる
# --- 2つなら散布図
mtcars %$% qplot(mpg)
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
# ビンを指定する
mtcars %$% qplot(mpg, binwidth = 4)
# ggplot関数で描くと以下のとおり
mtcars %>%
ggplot(aes(mpg)) +
geom_histogram(binwidth = 4)
# 準備:使用するデータセット
ToothGrowth %>% glimpse()
## Observations: 60
## Variables: 3
## $ len <dbl> 4.2, 11.5, 7.3, 5.8, 6.4, 10.0, 11.2, 11.2, 5.2, 7.0, 16....
## $ supp <fctr> VC, VC, VC, VC, VC, VC, VC, VC, VC, VC, VC, VC, VC, VC, ...
## $ dose <dbl> 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 1.0, 1....
# 数値を棒フラグ
# --- 数値をそのまま棒グラフにする
ToothGrowth %$% plot(supp, len)
# ちなみにxyを逆にすると上手くいかない
ToothGrowth %$% plot(y = supp, x = len)
# 箱ひげ図を直接作成するboxplot関数もある
ToothGrowth %>% boxplot(len ~ supp, data = .)
ToothGrowth %>% boxplot(len ~ supp + dose, data = .)
# 数値を棒フラグ(数値をそのまま棒グラフにする)
ToothGrowth %$% qplot(supp, len, geom = "boxplot")
# ggplot関数で描くと以下のとおり
ToothGrowth %>%
ggplot(aes(supp, len)) +
geom_boxplot()
# 準備:関数を定義
myfun <- function(xvar) 1 / (1 + exp(-xvar + 10))
# 変数xが-4から4に移動した際のグラフ
curve(expr = x ^ 3 - 5 * x, from = -4, to = 4)
# 独自関数をグラフ化
curve(myfun(x), from = 0, to = 20)
curve(1 - myfun(x), add = TRUE, col = "red")
# qplot関数をstat引数とgeom引数でコントロール
# qplot(c(0, 20), fun = myfun, stat = "function", geom = "line")
# ggplot関数で描くと以下のとおり
data.frame(x = c(0, 20)) %>%
ggplot(aes(x = x)) +
stat_function(fun = myfun, geom = "line")
X軸にカテゴリ変数
を、Y軸に数値
をマッピングして作成するY軸に個数をマッピングする「ヒストグラム」
と「棒グラフ」は明確に区別することgeom_bar()
で棒グラフを作成する
stat="identity"
を指定しなければ、グラフが表示されない# 準備:データセットの確認
# --- X:group Y:weight
pg_mean %>% print()
## group weight
## 1 ctrl 5.032
## 2 trt1 4.661
## 3 trt2 5.526
# グラフの作成
pg_mean %>%
ggplot(aes(group, weight)) +
geom_bar(stat = "identity")
連続値変数
の場合、系列がなくても0のグラフができる離散値変数
の場合、系列がなければ省略される# 準備:データセットの確認
# --- 「6」が存在しないのがポイント
BOD %>% print()
## Time demand
## 1 1 8.3
## 2 2 10.3
## 3 3 19.0
## 4 4 16.0
## 5 5 15.6
## 6 7 19.8
# 棒グラフの作成
# --- 時間を連続値変数のまま
BOD %>%
ggplot(aes(x = Time,y = demand)) +
geom_bar(stat = "identity")
# 棒グラフの作成
# --- 時間をファクター(離散値変数)に変換
BOD %>%
ggplot(aes(x = factor(Time),y = demand)) +
geom_bar(stat = "identity")
fill
は系列の中の色を指定するcolour
は枠線の色を指定する
color
ではなくイギリス式綴りのcolour
を使う# 系列に色を付ける
pg_mean %>%
ggplot(aes(group, weight)) +
geom_bar(stat = "identity", fill = "lightblue" , colour = "black")
geom_bar(position="dodge")
を指定することで水平方向に避けて描画する# 準備:データセットの確認
cabbage_exp[1:3] %>% print()
## Cultivar Date Weight
## 1 c39 d16 3.18
## 2 c39 d20 2.80
## 3 c39 d21 2.74
## 4 c52 d16 2.26
## 5 c52 d20 3.11
## 6 c52 d21 1.47
# 2つのカテゴリデータの棒グラフ
cabbage_exp %>%
ggplot(aes(x = Date, y = Weight, fill = Cultivar)) +
geom_bar(stat = "identity", position = "dodge")
折れ線グラフ
はX軸とY軸の両方が連続変数
である場合に使う手法時間
である場合は、特に時系列グラフ
と呼ばれるgeom_line()
で折れ線グラフを作成することができるX軸は連続データ
であることが前提なので、線形補完的に6が入力されている# 準備:データセットの確認
# --- "Time=6"がない点に注意
BOD %>% print()
## Time demand
## 1 1 8.3
## 2 2 10.3
## 3 3 19.0
## 4 4 16.0
## 5 5 15.6
## 6 7 19.8
# 折れ線グラフの作成
BOD %>% ggplot(aes(Time, demand)) + geom_line()
# 準備:Timeをカテゴリカル変数に変換
BOD1 <- BOD
BOD1$Time <- BOD1$Time %>% factor()
# 折れ線グラフの作成
# --- "6"がない点に注意
BOD1 %>% ggplot(aes(Time, demand, group = 1)) + geom_line()
geom_line()
では、Y軸の表示範囲はYの最小値から最大値に設定されている
ylim()
:最小値と最大値を任意に指定できるexpand_limits
:指定した数値を含むように従来の表示範囲を拡張# 最小値と最大値を任意に指定
BOD %>% ggplot(aes(Time, demand)) + geom_line() + ylim(0, max(BOD$demand))
# 指定した数値を含むように従来の表示範囲を拡張
BOD %>% ggplot(aes(Time, demand)) + geom_line() + expand_limits(y = 0)
geom_point()
を追加する# 準備:データセットの確認
BOD %>% print()
## Time demand
## 1 1 8.3
## 2 2 10.3
## 3 3 19.0
## 4 4 16.0
## 5 5 15.6
## 6 7 19.8
# 折れ線グラフに点を追加する
BOD %>% ggplot(aes(Time, demand)) + geom_line() + geom_point()
# グラフの表示
# --- 0-2000あたりのデータ密度が高くなっている
worldpop %>%
ggplot(aes(Year, Population)) +
geom_line() +
geom_point()
# 対数軸で表示
worldpop %>%
ggplot(aes(Year, Population)) +
geom_line() +
geom_point() +
scale_y_log10()
カテゴリごとに列方向に並べる
と複数系列の折れ線グラフを作成できるaes()
にカテゴリをfill引数
やcolour引数
でマッピングする# 準備1:データ集計
tg <- ToothGrowth %>%
group_by(supp, dose) %>%
summarise(length = mean(len)) %>%
print()
## Source: local data frame [6 x 3]
## Groups: supp [?]
##
## supp dose length
## <fctr> <dbl> <dbl>
## 1 OJ 0.5 13.23
## 2 OJ 1.0 22.70
## 3 OJ 2.0 26.06
## 4 VC 0.5 7.98
## 5 VC 1.0 16.77
## 6 VC 2.0 26.14
# 準備2:集計データの属性確認
tg %>% glimpse()
## Observations: 6
## Variables: 3
## $ supp <fctr> OJ, OJ, OJ, VC, VC, VC
## $ dose <dbl> 0.5, 1.0, 2.0, 0.5, 1.0, 2.0
## $ length <dbl> 13.23, 22.70, 26.06, 7.98, 16.77, 26.14
# suppをcolourにマッピング
tg %>%
ggplot(aes(x = dose, y = length, colour = supp)) +
geom_line()
# suppをlinetypeにマッピング
tg %>%
ggplot(aes(x = dose, y = length, linetype = supp)) +
geom_line()
geom_area()
を使用して、カテゴリカルデータをfill
にマッピングする{tidyr}
のgather()
で整形するケースが多くなる# 準備1:データセットの確認
uspopage %>% head()
## Year AgeGroup Thousands
## 1 1900 <5 9181
## 2 1900 5-14 16966
## 3 1900 15-24 14951
## 4 1900 25-34 12161
## 5 1900 35-44 9273
## 6 1900 45-54 6437
# 準備2:データセットの属性確認
uspopage %>% glimpse()
## Observations: 824
## Variables: 3
## $ Year <int> 1900, 1900, 1900, 1900, 1900, 1900, 1900, 1900, 1901...
## $ AgeGroup <fctr> <5, 5-14, 15-24, 25-34, 35-44, 45-54, 55-64, >64, <...
## $ Thousands <int> 9181, 16966, 14951, 12161, 9273, 6437, 4026, 3099, 9...
# データセットの作成
uspopage %>%
ggplot(aes(x = Year, y = Thousands, fill = AgeGroup)) +
geom_area()
geom_point
を使うことで散布図を作成できる
# 準備:使用データの確認
heightweight[, c("ageYear", "heightIn")] %>% glimpse()
## Observations: 236
## Variables: 2
## $ ageYear <dbl> 11.92, 12.92, 12.75, 13.42, 15.92, 14.25, 15.42, 11.8...
## $ heightIn <dbl> 56.3, 62.3, 63.3, 59.0, 62.5, 62.5, 59.0, 56.5, 62.0,...
# 散布図の作成
# --- プロットの形状やサイズは任意に指定できる
# --- デフォルトを使用する場合は`geom_point()`とする
heightweight %>%
ggplot(aes(ageYear, heightIn)) +
geom_point(shape=19)
shape=
)するための対応表は以下の通り
shape=16
よりshape=19
の方が滑らからしい(P75)
ファクター型データ(カテゴリ変数)
に対して行われる色
又は形状
で表現される
色
:aes(x =, y =, colour =)形状
:aes(x =, y =, shape =)サイズ
は連続データの概念なのでカテゴリデータには使用できない# 準備:使用データの確認
heightweight[, c("sex", "ageYear", "heightIn")] %>% glimpse()
## Observations: 236
## Variables: 3
## $ sex <fctr> f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f...
## $ ageYear <dbl> 11.92, 12.92, 12.75, 13.42, 15.92, 14.25, 15.42, 11.8...
## $ heightIn <dbl> 56.3, 62.3, 63.3, 59.0, 62.5, 62.5, 59.0, 56.5, 62.0,...
# 散布図の作成
# --- カテゴリを色で分ける
heightweight %>%
ggplot(aes(x = ageYear, y = heightIn, colour = sex)) +
geom_point()
# --- カテゴリを形状と色の両方で分ける
heightweight %>%
ggplot(aes(x = ageYear, y = heightIn, shape = sex, colour = sex)) +
geom_point()
連続データの大小関係
をプロットで表現することもできる色
又はサイズ
で表現される
色
:aes(x =, y =, colour =)サイズ
:aes(x =, y =, size =)形状
はカテゴリデータの概念なので連続データには使用できない# 準備:使用データの確認
heightweight[, c("weightLb", "ageYear", "heightIn")] %>% glimpse()
## Observations: 236
## Variables: 3
## $ weightLb <dbl> 85.0, 105.0, 108.0, 92.0, 112.5, 112.0, 104.0, 69.0, ...
## $ ageYear <dbl> 11.92, 12.92, 12.75, 13.42, 15.92, 14.25, 15.42, 11.8...
## $ heightIn <dbl> 56.3, 62.3, 63.3, 59.0, 62.5, 62.5, 59.0, 56.5, 62.0,...
# 散布図の作成
# --- 連続データを色で分ける
heightweight %>%
ggplot(aes(x = ageYear, y = heightIn, colour = weightLb)) +
geom_point()
# --- 連続データを色とサイズの両方で分ける
heightweight %>%
ggplot(aes(x = ageYear, y = heightIn, size = weightLb, colour = weightLb)) +
geom_point()
オーバープロット問題
データの密度
を表現する4つの方法がソリューションとなる
プロットの濃淡
で表現する
geom_point(alpha = )
で表現するalpha
の数値は1が半透明0%、0.1だと半透明90%# 準備1:データ数の確認
diamonds %>% dim()
## [1] 53940 10
# 準備2:グラフにデータをマッピング
sp <- diamonds %>% ggplot(aes(carat, price))
# 通常の散布図
# --- プロットが多すぎて黒塗りになっている
sp + geom_point()
# 散布図のプロットに透明度を適用
# --- 半透明:90%
sp + geom_point(alpha = 0.1)
# 散布図のプロットに透明度を適用
# --- 半透明:99%
sp + geom_point(alpha = 0.01)
bin
でクラスタの数(大きさ)を指定する# 準備:グラフにデータをマッピング
sp <- diamonds %>% ggplot(aes(carat, price))
# 散布図を長方形のクラスタ化
# --- bin=30で指定されているので荒い
# --- 色の濃淡が見分けにくい
# --- 凡例に最低値が表示されない(実データにゼロが含まれないため)
sp + stat_bin2d()
# 前のデータの問題点を解消
# --- bin=50として細かく表示
# --- scale_fill_gradientで色の濃淡と凡例の問題を解決
sp +
stat_bin2d(bins = 50) +
scale_fill_gradient(low = "lightblue", high = "red", limits = c(0, 6000))
{hexbin}
のstat_binhex()
を使うstat_bin2d()
と同様にデフォルトで使いやすいものではない# 準備1:新たなライブラリの参照
library(hexbin)
## Warning: package 'hexbin' was built under R version 3.3.2
# 準備2:グラフにデータをマッピング
sp <- diamonds %>% ggplot(aes(carat, price))
# 散布図を長方形のクラスタ化
# --- bin=30で指定されているので荒い
# --- 色の濃淡が見分けにくい
# --- 凡例に最低値が表示されない(実データにゼロが含まれないため)
sp + stat_binhex()
# 前のデータの問題点を解消
# --- bin=50として細かく表示
# --- scale_fill_gradientで色の濃淡と凡例の問題を解決
sp +
stat_binhex() +
scale_fill_gradient(low = "lightblue", high = "red",
breaks = c(0, 250, 500, 1000, 2000, 4000, 6000),
limits = c(0, 6000))
線形回帰
は唯一絶対のものではないloess(局所加重多項式)
になっている# 準備1:データセットの確認
heightweight %>% glimpse()
## Observations: 236
## Variables: 5
## $ sex <fctr> f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f...
## $ ageYear <dbl> 11.92, 12.92, 12.75, 13.42, 15.92, 14.25, 15.42, 11.8...
## $ ageMonth <int> 143, 155, 153, 161, 191, 171, 185, 142, 160, 140, 139...
## $ heightIn <dbl> 56.3, 62.3, 63.3, 59.0, 62.5, 62.5, 59.0, 56.5, 62.0,...
## $ weightLb <dbl> 85.0, 105.0, 108.0, 92.0, 112.5, 112.0, 104.0, 69.0, ...
# 準備2:基本プロットの作成
sp <- heightweight %>% ggplot(aes(ageYear, heightIn)) + geom_point()
sp
# デフォルトで散布図にフィッティングさせる
# --- loess(局所加重多項式)が適用される
sp + geom_smooth()
## `geom_smooth()` using method = 'loess'
# 線型回帰モデルの追加
# --- g1:信頼区間95%(デフォルト)を使用
# --- g2:信頼区間99%に設定
# --- g3:信頼区間を無効にする場合はse=FALSEにする(seは標準誤差)
# --- g4:g3の線をデフォルトの青色から黒色に変更する
g1 <- sp + geom_smooth(method = lm)
g2 <- sp + geom_smooth(method = lm, level = 0.99)
g3 <- sp + geom_smooth(method = lm, se = FALSE)
g4 <- sp + geom_smooth(method = lm, se = FALSE, colour = "black")
grid.arrange(g1, g2, g3, g4, nrow = 2, ncol = 2)
# 準備1:データセットの確認 (MASSパッケージより)
biopsy %>% glimpse()
## Observations: 699
## Variables: 11
## $ ID <chr> "1000025", "1002945", "1015425", "1016277", "1017023", "...
## $ V1 <int> 5, 5, 3, 6, 4, 8, 1, 2, 2, 4, 1, 2, 5, 1, 8, 7, 4, 4, 10...
## $ V2 <int> 1, 4, 1, 8, 1, 10, 1, 1, 1, 2, 1, 1, 3, 1, 7, 4, 1, 1, 7...
## $ V3 <int> 1, 4, 1, 8, 1, 10, 1, 2, 1, 1, 1, 1, 3, 1, 5, 6, 1, 1, 7...
## $ V4 <int> 1, 5, 1, 1, 3, 8, 1, 1, 1, 1, 1, 1, 3, 1, 10, 4, 1, 1, 6...
## $ V5 <int> 2, 7, 2, 3, 2, 7, 2, 2, 2, 2, 1, 2, 2, 2, 7, 6, 2, 2, 4,...
## $ V6 <int> 1, 10, 2, 4, 1, 10, 10, 1, 1, 1, 1, 1, 3, 3, 9, 1, 1, 1,...
## $ V7 <int> 3, 3, 3, 3, 3, 9, 3, 3, 1, 2, 3, 2, 4, 3, 5, 4, 2, 3, 4,...
## $ V8 <int> 1, 2, 1, 7, 1, 7, 1, 1, 1, 1, 1, 1, 4, 1, 5, 3, 1, 1, 1,...
## $ V9 <int> 1, 1, 1, 1, 1, 1, 1, 1, 5, 1, 1, 1, 1, 1, 4, 1, 1, 1, 2,...
## $ class <fctr> benign, benign, benign, benign, benign, malignant, beni...
# 準備2:0/1データの作成
X <- biopsy %>% mutate(classn = ifelse(class == "benign", 0, 1))
X %>% head()
## ID V1 V2 V3 V4 V5 V6 V7 V8 V9 class classn
## 1 1000025 5 1 1 1 2 1 3 1 1 benign 0
## 2 1002945 5 4 4 5 7 10 3 2 1 benign 0
## 3 1015425 3 1 1 1 2 2 3 1 1 benign 0
## 4 1016277 6 8 8 1 3 4 3 7 1 benign 0
## 5 1017023 4 1 1 3 2 1 3 1 1 benign 0
## 6 1017122 8 10 10 8 7 10 9 7 1 malignant 1
#
X %>%
ggplot(aes(V1, classn)) +
geom_point()
- 散布図に縁に1次元の散布図を示すラグ
を表示する - ラグは密度
は示すが度数
は示さないのでヒストグラムとは異なる
# 準備:データセットの確認
faithful %>% glimpse()
## Observations: 272
## Variables: 2
## $ eruptions <dbl> 3.600, 1.800, 3.333, 2.283, 4.533, 2.883, 4.700, 3.6...
## $ waiting <dbl> 79, 54, 74, 62, 85, 55, 88, 85, 51, 85, 54, 84, 78, ...
# 散布図にラグを追加
faithful %>%
ggplot(aes(eruptions, waiting)) +
geom_point() +
geom_rug()
# 散布図にラグを追加(ジッター追加)
faithful %>%
ggplot(aes(eruptions, waiting)) +
geom_point() +
geom_rug(position = "jitter", size = 0.2)
geom_text()
を使えば簡単# 準備1:データセットの作成&確認
X <- countries %>% filter(Year == 2009, healthexp > 2000) %T>% glimpse()
## Observations: 27
## Variables: 7
## $ Name <fctr> Andorra, Australia, Austria, Belgium, Canada, De...
## $ Code <fctr> AND, AUS, AUT, BEL, CAN, DNK, FIN, FRA, DEU, GRC...
## $ Year <int> 2009, 2009, 2009, 2009, 2009, 2009, 2009, 2009, 2...
## $ GDP <dbl> NA, 42130.82, 45555.43, 43640.20, 39599.04, 55933...
## $ laborrate <dbl> NA, 65.2, 60.4, 53.5, 67.8, 65.4, 60.9, 56.1, 59....
## $ healthexp <dbl> 3089.636, 3867.429, 5037.311, 5104.019, 4379.761,...
## $ infmortality <dbl> 3.1, 4.2, 3.6, 3.6, 5.2, 3.4, 2.5, 3.5, 3.5, 3.5,...
# 準備2:ベースとなる散布図の作成
sp <- X %>% ggplot(aes(healthexp, infmortality)) + geom_point()
sp
# 手動でラベルを付ける
# --- 個別にプロットを指定する必要があるので大変
sp +
annotate("text", x = 4350, y = 5.4, label = "Canada") +
annotate("text", x = 7400, y = 6.8, label = "USA")
# 一括でラベルを付ける
# --- デフォルトではラベルが重なるなどの問題がある
# --- サイズが解決策の1つとなる
sp + geom_text(aes(label = Name), size = 4)
バルーンプロット
がある
geom_point()
とscale_size_area()
を併せて使うgeom_histgram()
を使い、X軸に連続値データをマッピングする
# 準備:データセットの確認
faithful %>% glimpse()
## Observations: 272
## Variables: 2
## $ eruptions <dbl> 3.600, 1.800, 3.333, 2.283, 4.533, 2.883, 4.700, 3.6...
## $ waiting <dbl> 79, 54, 74, 62, 85, 55, 88, 85, 51, 85, 54, 84, 78, ...
# waitingのヒストグラム
faithful %>%
ggplot(aes(x = waiting)) +
geom_histogram()
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
データフレーム形式のデータ
を引数とする
NULL %>% ggplot()
とするとベクトル指定が可能となる# ベクトル指定でヒストグラム作成
NULL %>%
ggplot(aes(faithful$waiting)) +
geom_histogram(binwidth = 1)
annotate()
を使って座標上にテキストを追加する# 準備:散布図の作成
p <- faithful %>% ggplot(aes(eruptions, waiting)) + geom_point()
p %>% print()
# テキスト注釈の追加
p +
annotate("text", x = 3.0, y = 48, label = "Group 1") +
annotate("text", x = 4.5, y = 66, label = "Group 2")
annotate(geom = "text")
を使用し、parse = TRUE
を設定する# 準備:正規曲線のグラフ
p <- data.frame(x = c(-3, 3)) %>% ggplot(aes(x = x)) + stat_function(fun = dnorm)
p %>% print()
#テキスト注釈に数式を追加
p + annotate("text", x = 2, y = 0.3, parse = TRUE,
label = "frac(1, sqrt(2 * pi)) * e ^ {-x^2 / 2}")
geom_hline()
で水平線を、geom_vline()
で垂直線を追加することができるgeom_abline()
で傾きのある直線を追加することができる# 準備:基本グラフの作成
p <- heightweight %>% ggplot(aes(ageYear, heightIn, colour = sex)) + geom_point()
p %>% print()
# 水平線と垂直線を追加
p +
geom_hline(yintercept = 60) +
geom_vline(xintercept = 14)
# 傾きのある直線を追加する
p + geom_abline(intercept = 37.4, slope = 1.75)
annotate(geom = "segment")
を使用する# 準備1:データセットの確認
climate %>% glimpse()
## Observations: 499
## Variables: 6
## $ Source <chr> "Berkeley", "Berkeley", "Berkeley", "Berkeley", "Be...
## $ Year <dbl> 1800, 1801, 1802, 1803, 1804, 1805, 1806, 1807, 180...
## $ Anomaly1y <dbl> NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,...
## $ Anomaly5y <dbl> NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,...
## $ Anomaly10y <dbl> -0.435, -0.453, -0.460, -0.493, -0.536, -0.541, -0....
## $ Unc10y <dbl> 0.505, 0.493, 0.486, 0.489, 0.483, 0.475, 0.468, 0....
# 準備2:基本グラフの作成
p <- climate %>%
filter(Source == "Berkeley") %>%
ggplot(aes(Year, Anomaly10y)) +
geom_line()
p %>% print()
# グラフ上に線分を追加
p + annotate(geom = "segment", x = 1950, xend = 1980, y = -0.25, yend = -0.25)
annotate(geom = "rect")
を使用して網掛け領域を設定する# 準備1:データセットの確認
climate %>% glimpse()
## Observations: 499
## Variables: 6
## $ Source <chr> "Berkeley", "Berkeley", "Berkeley", "Berkeley", "Be...
## $ Year <dbl> 1800, 1801, 1802, 1803, 1804, 1805, 1806, 1807, 180...
## $ Anomaly1y <dbl> NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,...
## $ Anomaly5y <dbl> NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,...
## $ Anomaly10y <dbl> -0.435, -0.453, -0.460, -0.493, -0.536, -0.541, -0....
## $ Unc10y <dbl> 0.505, 0.493, 0.486, 0.489, 0.483, 0.475, 0.468, 0....
# 準備2:基本グラフの作成
p <- climate %>%
filter(Source == "Berkeley") %>%
ggplot(aes(Year, Anomaly10y)) +
geom_line()
p %>% print()
# 網掛け領域を指定する
p + annotate(geom = "rect", xmin = 1950, xmax = 1980,
ymin = -1, ymax = 1, alpha = 0.1, fill = "blue")
# 準備:データセットの作成
pg <-
PlantGrowth %>%
mutate(h1 = "no") %>%
mutate(h1 = if_else(.$group == "trt2", "yes", "no")) %T>% glimpse()
## Observations: 30
## Variables: 3
## $ weight <dbl> 4.17, 5.58, 5.18, 6.11, 4.50, 4.61, 5.17, 4.53, 5.33, 5...
## $ group <fctr> ctrl, ctrl, ctrl, ctrl, ctrl, ctrl, ctrl, ctrl, ctrl, ...
## $ h1 <chr> "no", "no", "no", "no", "no", "no", "no", "no", "no", "...
# 要素の色を指定する
pg %>%
ggplot(aes(group, weight, fill = h1)) +
geom_boxplot() +
scale_fill_manual(values = c("grey85", "#FFDDCC"), guide = FALSE)
# 準備1:基本プロットの作成
p <- heightweight %>%
ggplot(aes(x = ageYear, y = heightIn)) +
geom_point()
# 準備2:プロットの確認
# --- グラフタイトルがついていない
p %>% print()
# グラフタイトルを付ける
# --- 左:改行なし 右:改行あり(上手くいかず)
p1 <- p + ggtitle("Age and Height of SchoolChildren")
p2 <- p + ggtitle("Age and Height \n of SchoolChildren")
grid.arrange(p1, p1, ncol = 2)
# 準備1:基本プロットの作成
p <- heightweight %>%
ggplot(aes(x = ageYear, y = heightIn)) +
geom_point()
# 準備2:プロットの確認
# --- グラフタイトルがついていない
p %>% print()
#
p + theme(axis.title.x = element_text(size = 16,
lineheight = 0.9,
family = "Times",
face = "bold.italic",
colour = "red"))
## Warning in grid.Call(L_textBounds, as.graphicsAnnot(x$label), x$x, x$y, :
## Windows のフォントデータベースにフォントファミリが見付かりません
## Warning in grid.Call(L_textBounds, as.graphicsAnnot(x$label), x$x, x$y, :
## Windows のフォントデータベースにフォントファミリが見付かりません
## Warning in grid.Call(L_textBounds, as.graphicsAnnot(x$label), x$x, x$y, :
## Windows のフォントデータベースにフォントファミリが見付かりません
guides()
を使って凡例を消すスケールを指定する# 準備1:基本プロットの作成
p <- PlantGrowth %>%
ggplot(aes(x = group, y = weight, fill = group)) +
geom_boxplot()
# プロットの確認
# --- fillの凡例がついている(系列色)
p %>% print()
# fillの凡例を消す
p + guides(fill = FALSE)
theme(legend.position="")
により位置を変更できる
# 準備1:基本プロットの作成
p <- PlantGrowth %>%
ggplot(aes(x = group, y = weight, fill = group)) +
geom_boxplot() +
scale_fill_brewer(palette = "Pastel2")
# プロットの確認
# --- 右端に凡例が表示される
p %>% print()
# 凡例の位置を上部に変更
p + theme(legend.position = "top")
scale_fill_discrete()
のlimit引数
で凡例の順番をコントロールできる# 準備1:基本プロットの作成
p <- PlantGrowth %>%
ggplot(aes(x = group, y = weight, fill = group)) +
geom_boxplot()
# 準備2:基本プロットの確認
p %>% print()
# 項目順の変更
p + scale_fill_discrete(limits = c("trt1", "trt2", "ctr1"))
guides(fill = guide_legend(reverse = TRUE))
を追加する (fillの場合)
colour
やsize
など選択# 準備1:基本プロットの作成
p <- PlantGrowth %>%
ggplot(aes(x = group, y = weight, fill = group)) +
geom_boxplot()
# 準備2:基本プロットの確認
p %>% print()
# 凡例の順序を反転させる
p + guides(fill = guide_legend(reverse = TRUE))
guides(fill = guide_legend(reverse = TRUE))
を追加する (fillの場合)
colour
やsize
など選択# 準備1:基本プロットの作成
p <- PlantGrowth %>%
ggplot(aes(x = group, y = weight, fill = group)) +
geom_boxplot()
# 準備2:基本プロットの確認
p %>% print()
# 凡例のタイトルを「Condition」に設定
p + labs(fill = "Condition")
guides(fill = guide_legend(reverse = TRUE))
を追加する (fillの場合)
colour
やsize
など選択# 準備1:基本プロットの作成
p <- PlantGrowth %>%
ggplot(aes(x = group, y = weight, fill = group)) +
geom_boxplot()
# 準備2:基本プロットの確認
p %>% print()
# 凡例タイトルのテキストを変更したい
p + theme(legend.title = element_text(face = "italic",
family = "Times",
colour = "red",
size = 14))
## Warning in grid.Call(L_textBounds, as.graphicsAnnot(x$label), x$x, x$y, :
## Windows のフォントデータベースにフォントファミリが見付かりません
## Warning in grid.Call.graphics(L_text, as.graphicsAnnot(x$label), x$x, x
## $y, : Windows のフォントデータベースにフォントファミリが見付かりません
guides(fill = guide_legend(title = NULL))
を追加する# 準備1:基本プロットの作成
p <- PlantGrowth %>%
ggplot(aes(x = group, y = weight, fill = group)) +
geom_boxplot()
# 準備2:基本プロットの確認
p %>% print()
# 凡例タイトルのテキストを変更したい
p + guides(fill = guide_legend(title = NULL))
scale_fill_discrete()
でスケールを指定する際にlabels引数
を指定する# 準備1:基本プロットの作成
p <- PlantGrowth %>%
ggplot(aes(x = group, y = weight, fill = group)) +
geom_boxplot()
# 準備2:基本プロットの確認
p %>% print()
# 凡例タイトルのテキストを変更したい
p + scale_fill_discrete(labels = c("Control", "Treatment 1", "Treatment2"))
theme(legend.text = element_text()
を使う# 準備1:基本プロットの作成
p <- PlantGrowth %>%
ggplot(aes(x = group, y = weight, fill = group)) +
geom_boxplot()
# 準備2:基本プロットの確認
p %>% print()
# 凡例ラベルの体裁を変更
#p + theme(legend.text = element_text(face = "italic",
# family = "Times",
# colour = "red",
# size = 14))
\n
を文字列に組み込むことで開業を表現する# 準備1:基本プロットの作成
p <- PlantGrowth %>%
ggplot(aes(x = group, y = weight, fill = group)) +
geom_boxplot()
# 準備2:基本プロットの確認
p %>% print()
p + scale_fill_discrete(labels = c("Control",
"Type 1\ntreatment",
"Type 2\ntreatment"))
ファセット
とは、データをグループごとにグラフに並べて表示する方法# 準備1:データセットの確認
mpg %>% glimpse()
## Observations: 234
## Variables: 11
## $ manufacturer <chr> "audi", "audi", "audi", "audi", "audi", "audi", "...
## $ model <chr> "a4", "a4", "a4", "a4", "a4", "a4", "a4", "a4 qua...
## $ displ <dbl> 1.8, 1.8, 2.0, 2.0, 2.8, 2.8, 3.1, 1.8, 1.8, 2.0,...
## $ year <int> 1999, 1999, 2008, 2008, 1999, 1999, 2008, 1999, 1...
## $ cyl <int> 4, 4, 4, 4, 6, 6, 6, 4, 4, 4, 4, 6, 6, 6, 6, 6, 6...
## $ trans <chr> "auto(l5)", "manual(m5)", "manual(m6)", "auto(av)...
## $ drv <chr> "f", "f", "f", "f", "f", "f", "f", "4", "4", "4",...
## $ cty <int> 18, 21, 20, 21, 16, 18, 18, 18, 16, 20, 19, 15, 1...
## $ hwy <int> 29, 29, 31, 30, 26, 26, 27, 26, 25, 28, 27, 25, 2...
## $ fl <chr> "p", "p", "p", "p", "p", "p", "p", "p", "p", "p",...
## $ class <chr> "compact", "compact", "compact", "compact", "comp...
facet_grid()
かfacet_wrap()
を使うfacet_grid
:垂直or水平方向にグラフを分割する
facet_wrap
:サブプロットが順番に表示される
# 準備:基本プロットの作成
p <- mpg %>% ggplot(aes(x = displ, y = hwy)) + geom_point()
p %>% print()
# 行方向を「drv」で分割
p + facet_grid(drv ~ .)
# 列方向を「cyl」で分割
p + facet_grid(. ~ cyl)
# 行方向を「drv」 + 列方向を「cyl」で分割
p + facet_grid(drv ~ cyl)
# 「class」ごとにサブグラフで表示
p + facet_wrap(~ class)
# 準備:基本プロットの作成
p <- mpg %>% ggplot(aes(x = displ, y = hwy)) + geom_point()
p %>% print()
# ファセットを適用
p + facet_grid(drv ~ cyl)
# y軸をフリースケールに変更
p + facet_grid(drv ~ cyl, scales = "free_y")
# x軸とy軸をフリースケールに変更
p + facet_grid(drv ~ cyl, scales = "free")
mutate()
と{forcat}のfct_recode()
を使うと簡単に操作できる# 元データのコピーを作成
mpg2 <- mpg
# カテゴリデータを変更
mpg2 <-
mpg %>%
mutate(drv = fct_recode(drv, "4wd" = "4", "Front" = "f", "Rear" = "r"))
# 新データをプロット
p1 <- mpg %>% ggplot(aes(x = displ, y = hwy)) + geom_point() + facet_grid(drv ~ .)
p2 <- mpg2 %>% ggplot(aes(x = displ, y = hwy)) + geom_point() + facet_grid(drv ~ .)
grid.arrange(p1, p2, ncol = 2)
テーマシステム
を使うとテキスト体裁や背景体裁を自由に制御できる# 準備:ファセットを適用したグラフ
p <- cabbage_exp %>%
ggplot(aes(x = Cultivar, y = Weight)) +
geom_bar(stat = "identity") +
facet_grid(. ~ Date)
p %>% print()
# テーマシステムの適用
p + theme(strip.text = element_text(face = "bold",
size = rel(1.5)),
strip.background = element_rect(fill = "lightblue",
colour = "black",
size = 1)
)
{dplyr}
や{tidyr}
で処理可能