matplot 1 (iris)
x <- lapply(iris[-5], function(v)tapply(v, iris$Species, sum))
(dat <- setNames(as.data.frame(Reduce(cbind, x)), names(x)))
## Sepal.Length Sepal.Width Petal.Length Petal.Width
## setosa 250.3 171.4 73.1 12.3
## versicolor 296.8 138.5 213.0 66.3
## virginica 329.4 148.7 277.6 101.3
lab <- rownames(dat)
matplot(t(dat), type = "b", pch=16, lty = 1, xaxt="n", ylab="")
axis(side = 1, at = c(1,2,3,4), labels = names(x))

matplot 2 (orange)
dat <- Orange
wdat <- reshape(dat, idvar = "age", timevar="Tree",
direction = "wide")
names(wdat) <- c("age", paste0("Tree", 1:5))
# なるべくパッケージを使わない
#wdat <- tidyr::spread(dat, key = "Tree", value = "circumference")
matplot(x = wdat$age, wdat[-1], type = "b",pch=16, lty = 1, xlab="age", ylab="circumference")

matplot 3
- x軸が一様でない場合
- NAがある場合はサブセットにsplitした後で除去する
# サンプルデータ
x <- rep(LETTERS[1:5], c(3,5,4,6,5))
v <- rnorm(x, mean = 10, sd = 1)
tv <- unlist(lapply(c(3,5,4,6,5), function(x){1:x}))
(dat <- data.frame(x,tv,v))
## x tv v
## 1 A 1 11.710872
## 2 A 2 10.015164
## 3 A 3 9.928121
## 4 B 1 10.189320
## 5 B 2 10.944826
## 6 B 3 10.334120
## 7 B 4 9.308887
## 8 B 5 9.816772
## 9 C 1 10.750040
## 10 C 2 9.536793
## 11 C 3 10.128946
## 12 C 4 8.253686
## 13 D 1 11.469020
## 14 D 2 9.814882
## 15 D 3 9.343242
## 16 D 4 10.901135
## 17 D 5 9.053860
## 18 D 6 11.821564
## 19 E 1 10.380739
## 20 E 2 9.982638
## 21 E 3 11.392197
## 22 E 4 10.194946
## 23 E 5 10.645045
# データフレーム分割
idx <- dat$x
dats <- split(dat, f = idx)
vcol <- 1:nlevels(factor(idx))
# 範囲
xlm <- range(dat$tv)
ylm <- range(dat$v)
# ループ処理
xlb <- "time" ; ylb <- "value"
for(i in seq_along(dats)){
x <- dats[[i]]
if(i == 1){
matplot(x = x$tv, y = x$v,
type = "b",pch=16, lty = 1, xlim = xlm, ylim = ylm,
col = vcol[i], xlab=xlb, ylab = ylb)
}else{
matplot(x = x$tv, y = x$v, add = TRUE,
type = "b",pch=16, lty = 1, xlim = xlm, ylim = ylm,
col = vcol[i], xlab = "", ylab ="")
}
}

geom_line orange
library(ggplot2)
ggplot(Orange, aes(x = age, y = circumference, colour = Tree)) +
geom_line(linewidth = 1) +
scale_color_manual(values = 1:5) +
theme_bw()
