LatticeはRに標準添付のライブラリなので,どんな環境でも使えることが期待できる.
まずデータを準備する.melt
を使うと扱いやすい形に変換できて便利.
library(lattice)
library(reshape)
data(iris)
head(iris)
## Sepal.Length Sepal.Width Petal.Length Petal.Width Species
## 1 5.1 3.5 1.4 0.2 setosa
## 2 4.9 3.0 1.4 0.2 setosa
## 3 4.7 3.2 1.3 0.2 setosa
## 4 4.6 3.1 1.5 0.2 setosa
## 5 5.0 3.6 1.4 0.2 setosa
## 6 5.4 3.9 1.7 0.4 setosa
melted.iris <- melt(iris)
## Using Species as id variables
head(melted.iris)
## 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
確率密度分布
sepal.length <- subset(melted.iris, variable="Sepal.Length")
print(densityplot(sepal.length$value, groups=sepal.length$Species, auto.key=T))
凡例を横に並べる
print(densityplot(sepal.length$value, groups=sepal.length$Species, auto.key=list(column=3)))
グリッドを入れる
panelを書く順番でグリッドが表に来るか裏に来るかが決まる.
print(densityplot(sepal.length$value, groups=sepal.length$Species, auto.key=TRUE,
panel=function(...){panel.densityplot(...); panel.grid(h=-1, v=-1)}))
色を変える
col
で色を変えようとしても凡例の色が変わらないので,ちょっと手を入れる必要がある
new.col <- rainbow(3)
par.settings <- list(superpose.line=list(col=new.col))
print(densityplot(sepal.length$value, groups=sepal.length$Species,
par.settings=par.settings, auto.key=TRUE))
参考: http://www.magesblog.com/2012/12/changing-colours-and-legends-in-lattice.html
密度分布の下にある点を取り除く
点の数が多すぎると PDF にしたときに重くなってしまうので,取り除いてお
く.
print(densityplot(sepal.length$value, groups=sepal.length$Species,
plot.points = FALSE, auto.key=TRUE))
並べる
print(densityplot(~melted.iris$value|factor(melted.iris$variable), groups=melted.iris$Species, auto.key=TRUE))
並べるけど,軸は独立させる
print(densityplot(~melted.iris$value|factor(melted.iris$variable), groups=melted.iris$Species,
auto.key=TRUE, scales=list(x="free")))
print(densityplot(~melted.iris$value|factor(melted.iris$variable), groups=melted.iris$Species,
auto.key=TRUE, scales=list(x="free", y="free")))
平行線図
線の数が多いときはalpha
で薄くしておくと良い感じになる.
parallelplot(~iris[1:4], alpha=0.4)
ここで,Min/MaxはPetal.Width, Petal.Length, Sepal.Width, Sepal.Length
のそれぞれで最大値,最小値が計算されている.なんらかの時間経過が見たい
ときなど,スケールが変わってしまっては困るときは要注意.上手い解決法が
分からないので,とりあえずアドホックな方法として最小値と最大値を全体に
いれることで対処している.
iris.tmp <- data.frame(iris)[1:4]
iris.tmp["max",] <- rep(max(iris.tmp), times=dim(iris.tmp)[2])
iris.tmp["min",] <- rep(min(iris.tmp), times=dim(iris.tmp)[2])
parallelplot(~iris.tmp, alpha=0.4)