プロット作成
- Rには標準で多様なプロットを作成可能
- 様々なところで説明されています
- 今日は可視化のパッケージ
{ggplot2}
を紹介します
さっそくプロット
library(ggplot2)
ggplot(iris, aes(y=Petal.Length, x=Sepal.Length)) +
geom_point()
解説
ggplot(iris, aes(y=Petal.Length, x=Sepal.Length)) +
geom_point()
ggplot2はレイヤー構造
- 一行目: 基本レイヤー
- 可視化するデータを指定します
- aes()の中で、x軸の変数とy軸の変数を指定
- 二行目: プロット方法
geom_point()
で「散布図書いて」となる
- 他のは後述
水準ごとで分けたい
ggplot(iris, aes(y=Petal.Length, x=Sepal.Length, col=Species)) +
geom_point()
- Speciesの内容ごとで色分けされた!
- aes()内に
col=Species
を追加
- これは「色をSpeciesで塗り分けて」という意味になる
ラベルを設定したい
ggplot(iris, aes(y=Petal.Length, x=Sepal.Length, col=Species)) +
geom_point() +
labs(title="iris-tan", x="yokoyoko", y="tatetate")
- 表のタイトル、x軸ラベル、y軸ラベルが設定されます
- このほか様々な設定が可能です
背景テーマ変更 + 文字を大きく
ggplot(iris,aes(y=Petal.Length,x=Sepal.Length, col=Species)) +
geom_point() +
theme_bw(base_size = 20)
- theme_*でテーマ設定
- theme_bw()は黒白テーマ
- base_sizeで基本の文字サイズ変更(デフォルトは12)
- base_familyでフォントファミリー変更可能(省略)
箱ひげ図を出したい
ggplot(iris, aes(y=Petal.Length,x=Species)) +
geom_boxplot()
箱ひげ図にさらに追加
ggplot(iris, aes(y=Petal.Length,x=Species)) +
geom_boxplot() + geom_jitter()
棒グラフを出したい(度数分布表)
ggplot(iris, aes(Petal.Length)) +
geom_bar()
- geom_bar()でバーチャート
- ターゲット変数を基本レイヤーのaes()内で指定
- この場合は各値の頻度を累積してカウントしてます
## stat_bin: binwidth defaulted to range/30. Use 'binwidth = x' to adjust this.
棒グラフを出したい(平均値の棒グラフ)
ggplot(iris, aes(y=Petal.Length, x=Species)) +
stat_summary(fun.y=mean,geom="bar")
- stat_summary()で、データを要約して可視化
- おおざっぱに例えると「f(y)=mean(y)として要約して棒にして」