複数のboxplotを一度に作成する

References

課題

データセット内の複数の変数に対して一度にboxplot描いてしまいたいと言うもの。個人的にはmelt()をして複数の変数名を一つのvariable変数にまとめて、値を一つのvalue変数にまとめる、reshape2::melt()のアプローチがグラフ化には向いているように思う。そして、グラフ化はggplot2!と思ったが、書式の分かりやすさはlatticeが最強かもしれない。

データ読み込み

data(iris)

reshape2::melt()でデータをとかす

library(reshape2)
iris.melt <- melt(iris)
head(iris.melt)
  Species     variable value
1  setosa Sepal.Length   5.1
2  setosa Sepal.Length   4.9
3  setosa Sepal.Length   4.7
4  setosa Sepal.Length   4.6
5  setosa Sepal.Length   5.0
6  setosa Sepal.Length   5.4

ggplot2で一度にプロット

library(ggplot2)
ggplot(data = iris.melt, mapping = aes(x = Species, y = value)) +
    layer(geom = "boxplot", stat = "boxplot") +
    facet_wrap(~variable, ncol = 2, scales = "free") +
    theme_bw()

plot of chunk unnamed-chunk-4

lattice最強説

library(lattice)
bwplot(value ~ Species | variable, data = iris.melt)

plot of chunk unnamed-chunk-5

関数化

aes_string()を使うとid.varsをggplot()の中にも再利用できた。

multi.boxplot <- function(data, id.vars, ncol) {
    require(reshape2)
    require(ggplot2)

    data.melt <- melt(data, id.vars = id.vars)

    ggplot(data = data.melt, mapping = aes_string(x = id.vars, y = "value")) +
        layer(geom = "boxplot", stat = "boxplot") +
        facet_wrap(~ variable, ncol = ncol, scales = "free") +
        theme_bw()
}

irisで試してみる

multi.boxplot(data = iris, id.vars = "Species", ncol = 2)

plot of chunk unnamed-chunk-7

他のデータセットで試してみる

library(survival)
data(pbc)

multi.boxplot(data = pbc[,c("sex","age","bili","chol","albumin","copper","alk.phos","ast","trig")],
              id.vars = "sex", ncol = 4)

plot of chunk unnamed-chunk-8