timeSeries型で二つの系列をプロットする方法

How to plot two series with timeSeries type in R programing.

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

timeSeries Class
timeSeries Class

ラベルをつけたい場合

これもgparsに指定するとできる

ts.plot(x, y,gpars=list(xlab="year", ylab="random value", col=c("red", "blue")))

Results

addlabel
add label

線を太くしたい場合:lwd (line width)

これもgparsに指定するとできる

ts.plot(x, y,gpars=list(xlab="year", ylab="random value", lwd=c(1:4), col=c("red", "blue")))

Reuslts

f:id:datablogger:20200326210906p:plain
boldline

cbindを使って結合する方法

comb_ts <- cbind(x,y) # カラムの大きさが同じであることが前提
plot.ts(comb_ts, plot.type = "single")

cbindplot
cbindplot

ちなみに

> 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

multiplot
multiplot

一つの系列を点にする

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

pointwithline
pointLine

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

histogram_line_plot
ヒストグラムとタイムラインプロット

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")

Results

ヒストグラム・折れ線プロット
ヒストグラム・折れ線プロット