データセット内の複数の変数に対して一度にboxplot描いてしまいたいと言うもの。個人的にはmelt()をして複数の変数名を一つのvariable変数にまとめて、値を一つのvalue変数にまとめる、reshape2::melt()のアプローチがグラフ化には向いているように思う。そして、グラフ化はggplot2!と思ったが、書式の分かりやすさはlatticeが最強かもしれない。
data(iris)
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
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()
library(lattice)
bwplot(value ~ Species | variable, data = iris.melt)
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)
他のデータセットで試してみる
library(survival)
data(pbc)
multi.boxplot(data = pbc[,c("sex","age","bili","chol","albumin","copper","alk.phos","ast","trig")],
id.vars = "sex", ncol = 4)