緑色の本のp.119に載っている図と似たものを書こうとして、
d <- data.frame(q = rep(c("q0.1", "q0.3", "q0.8"), c(9, 9, 9)), p = c(dbinom(0:8, 8, 0.1), dbinom(0:8, 8, 0.3), dbinom(0:8, 8, 0.8)), y = rep(0:8, 3))
というようなデータを準備したものの、baseパッケージではどうプロットしたら良いものか若干悩んだ。
baseの例
# base matplot(reshape(d, timevar = "q", idvar = "y", direction = "wide")[, -1], ylab = "p", xlab = "y", xaxt = "n", type = "b", pch = 16, lty = 1) axis(1, at = 1:9, labels = 0:8) legend("topright", inset = 0.05, legend = c("q = 0.1", "q = 0.3", "q = 0.8"), col = 1:3, pch = 1, box.lty = 0)
linesで重ねる方法もあるけどいずれにせよ面倒だし使い回ししにくい。もっと良い方法はないものか。
続いてlatticeで描いてみた。
# lattice library(lattice) xyplot(p ~ y, data = d, group = q, type = "b", auto.key = list(text =c("q = 0.1", "q = 0.3", "q = 0.8")))
凡例の編集をしようと思わなければ書式が素直で一番理解しやすい様に思う。
ggplot2
# ggplot2 # install.packages("ggplot2") library(ggplot2) ggplot(data = d, aes(x = y, y = p, col = q)) + geom_point() + geom_line() + scale_color_hue(label = c(q0.1 = "q = 0.1", q0.3 = "q = 0.3", q0.8 = "q = 0.8"))
latticeとさほど手間は変わらないけど、ggplot2はどうも覚えにくい気がする。初心者にaes()とかどう教えたら良いのかと毎回悩む。