2017-03-27 1 views
3

私は、独自のx軸ラベルやメインタイトルを書くことによってプロットを修正する通常の方法にはかなり精通していますが、時系列分解の結果をプロットするときに出力をカスタマイズできませんでした。例えば 分解された時系列のプロットでタイトル、軸ラベルなどをカスタマイズする方法

library(TTR) 
t <- ts(co2, frequency=12, start=1, deltat=1/12) 
td <- decompose(t) 
plot(td) 
plot(td, main="Title Doesn't Work") # gets you an error message 

は自分のデータであなたなど観測時系列、トレンド、の素敵な、基本的なプロットを与える(水面下の深さの変化)、しかし、私は思います(例えば、「観察された」の場合はylim = c(40,0)、「傾向」の場合はylim = c(18,12))、「季節」を「干満」に変更して、 x軸の単位( '時間(日)')を含めるとともに、数字をよりわかりやすいタイトルにします。

私の印象は、私がやっている時系列解析の種類はかなり基本的で、最終的にはもっと良いグラフィカルコントロールを使って別のパッケージを使うほうが良いかもしれないが、ts()私が今できる場合(ええ、ケーキと消費)分解してください。これはあまりにも恐ろしい得ることはないと仮定します。

これを行う方法はありますか?

ありがとうございます!ピート

答えて

4

あなたはそれはあなたが(tdのクラスである)クラスdecomposed.tsのオブジェクトにplotを実行したときに送出されますplot「法」だ(plot.decomposed.ts機能を変更することができます。

getAnywhere(plot.decomposed.ts) 
function (x, ...) 
{ 
    xx <- x$x 
    if (is.null(xx)) 
     xx <- with(x, if (type == "additive") 
      random + trend + seasonal 
     else random * trend * seasonal) 
    plot(cbind(observed = xx, trend = x$trend, seasonal = x$seasonal, random = x$random), 
     main = paste("Decomposition of", x$type, "time series"), ...) 
} 

上記のコードでは、関数がタイトルをハードコードすることに注意してください。私たち自身のタイトルを選択できるように修正しましょう:

my_plot.decomposed.ts = function(x, title="", ...) { 
    xx <- x$x 
    if (is.null(xx)) 
    xx <- with(x, if (type == "additive") 
     random + trend + seasonal 
     else random * trend * seasonal) 
    plot(cbind(observed = xx, trend = x$trend, seasonal = x$seasonal, random = x$random), 
     main=title, ...) 
} 

my_plot.decomposed.ts(td, "My Title") 

enter image description here

ここでプロットのggplotバージョンがあります。 ggplotにはデータフレームが必要です。最初のステップでは分解された時系列をデータフレーム形式にしてプロットします。

library(tidyverse) # Includes the packages ggplot2 and tidyr, which we use below 

# Get the time values for the time series 
Time = attributes(co2)[[1]] 
Time = seq(Time[1],Time[2], length.out=(Time[2]-Time[1])*Time[3]) 

# Convert td to data frame 
dat = cbind(Time, with(td, data.frame(Observed=x, Trend=trend, Seasonal=seasonal, Random=random))) 

ggplot(gather(dat, component, value, -Time), aes(Time, value)) + 
    facet_grid(component ~ ., scales="free_y") + 
    geom_line() + 
    theme_bw() + 
    labs(y=expression(CO[2]~(ppm)), x="Year") + 
    ggtitle(expression(Decomposed~CO[2]~Time~Series)) + 
    theme(plot.title=element_text(hjust=0.5)) 

enter image description here

+0

これは素晴らしいです...ありがとう! –

+0

完了!もう一度感謝します... –

関連する問題