timeSeries型で二つの系列をプロットする方法
How to plot two series with timeSeries type in R programing.
- ts.plot の引数に複数のtimeseriesを渡す
- ラベルをつけたい場合
- 線を太くしたい場合:lwd (line width)
- cbindを使って結合する方法
- 2系列を2段に分けるcbind + multiple
- 一つの系列を点にする
- timeSeriesの一つの系列だけヒストグラムにする
- timeSeriesの一つの系列だけヒストグラムにする
ts.plot の引数に複数のtimeseriesを渡す
ts.plot(..., gpars = list())を利用。
set.seed(1) x = ts(rnorm(20), frequency = 12, start = c(2002, 2)) y = ts(rnorm(20), frequency = 12, start = c(2002, 2)) ts.plot(x, y, gpars = list(col = c("black", "blue")))
- gparsは、プロットのグラフィックコンポーネントを指定できるグラフィックパラメーター。ここでは色を指定
Reuslts
ラベルをつけたい場合
これもgparsに指定するとできる
ts.plot(x, y,gpars=list(xlab="year", ylab="random value", col=c("red", "blue")))
Results
線を太くしたい場合:lwd (line width)
これもgparsに指定するとできる
ts.plot(x, y,gpars=list(xlab="year", ylab="random value", lwd=c(1:4), col=c("red", "blue")))
Reuslts
cbindを使って結合する方法
comb_ts <- cbind(x,y) # カラムの大きさが同じであることが前提 plot.ts(comb_ts, plot.type = "single")
ちなみに
> str(comb_ts)
とすると
Time-Series [1:20, 1:2] from 2002 to 2004: -0.626 0.184 -0.836 1.595 0.33 ... - attr(*, "dimnames")=List of 2 ..$ : NULL ..$ : chr [1:2] "x" "y"
2系列を2段に分けるcbind + multiple
comb_ts <- cbind(x,y) # カラムの大きさが同じであることが前提 str(cmb_ts) plot.ts(comb_ts, plot.type = "multiple")
Results
一つの系列を点にする
ts.plot(x, gpars=list(xlab="year", ylab="random value", lwd=c(1:4), col=c("red"),type="l")) points(y, pch = 19, col = "red")
Reuslts
timeSeriesの一つの系列だけヒストグラムにする
ヒストグラムとラインプロットを組み合わせる
set.seed(1) x = ts(rnorm(20), frequency = 12, start = c(2002, 2)) y = ts(rnorm(20), frequency = 12, start = c(2002, 2)) ts.plot(x, gpars = list(col = c("black" ))) lines(y,col="green",type="h")
Reuslts
timeSeriesの一つの系列だけヒストグラムにする
ヒストグラムとラインプロットを組み合わせる
set.seed(1) x = ts(rnorm(20), frequency = 12, start = c(2002, 2)) y = ts(rnorm(20), frequency = 12, start = c(2002, 2)) days <- as.Date(x) months <- strftime(days,"%Y/%m") df.bar <- barplot(as.vector(x), main = "Return of Assets", xlab = "Days", ylab = "Return", names.arg= months, col = "gray") lines(x = df.bar, y = as.vector(y),col="red",type="o")