LoginSignup
0
0

More than 3 years have passed since last update.

Rのggplot2で可視化

Posted at

はじめに

Rの可視化パッケージであるggplot2を用いてデータの可視化を行った。使うデータについてはこちらの記事を参考にして下さい。df というdata.frame型の変数に1000人分の性別、身長、体重、血液型のデータがある状況で可視化を行っていく。

データの中身の確認とパッケージの読み込み

まずはデータフレームの中身とデータ数を確認する。

コード
str(df)
出力
'data.frame':   1000 obs. of  4 variables:
 $ SEX   : chr  "female" "male" "female" "male" ...
 $ HEIGHT: num  160 171 161 175 157 ...
 $ WEIGHT: num  47.3 65.7 55.4 86.6 54.3 ...
 $ BLOOD : chr  "O" "A" "O" "B" ...

想定通りのデータができてそう。次いでggplot2の展開をする。

コード
library(ggplot2)

これで準備が整った。

散布図

コード
g <- ggplot(df, aes(x = WEIGHT, y = HEIGHT)) #プロットに使うデータの指定
g <- g + geom_point() #散布図を指定
plot(g) #プロット

R_Scatter_plot.png

男女で色分けした散布図は以下の通り。

コード
g <- ggplot(df, aes(x = WEIGHT, y = HEIGHT, color = SEX)) #グループとして性別を選択
g <- g + geom_point()
plot(g)

R_Scatter_plot_mf.png

男女の違いで微妙に集団が分かれているのが分かる。

次は血液型によって形を変えつつ、軸の名前やタイトルをつけてみる。

コード
g <- ggplot(df, aes(x = WEIGHT, y = HEIGHT, color = SEX, shape = BLOOD))
g <- g + labs(title = "1000人のサンプルデータ",
              subtitle = "身長、体重の相関",
              caption =  "ここに図のキャプションについてコメントする",
              x = "体重 [kg]",
              y = "身長 [cm]",
              color = "性別",
              shape = "血液型")
g <- g + geom_point()
plot(g)

R_Scatter_plot_mf_bt.png

ヒストグラム

散布図と同様に色分け、binの数の指定などをしていくと以下の様になる。

コード
g <- ggplot(df, aes(x = HEIGHT, fill = SEX))
g <- g + geom_histogram(bins = 30)
plot(g)

R_histgram.png

これを男女に分けたヒストグラムを作ると、以下の様になる。

コード
g <- ggplot(df, aes(x = HEIGHT))
g <- g + facet_grid(rows = vars(SEX))
g <- g + geom_histogram(bins = 30)
plot(g)

R_histgram_facet.png

男女共に正規分布に従っているのが分かる。

箱ひげ図

血液型に対する体重の箱ひげ図を作ってみる。

コード
g <- ggplot(df, aes(x = BLOOD, y = WEIGHT))
g <- g + geom_boxplot()
plot(g)

R_boxplot.png

もちろん血液型で分布に差が無いことが分かる。

おわりに

ggplot2でのデータの可視化を行ってみた。数行のコマンドで非常にきれいな図が作れるので、これからは可視化には積極的にggplot2を使って行きたいと思う。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0