2013-12-16 145 views
7
x=read.table(text=" Qtr1 Qtr2 Qtr3 Qtr4 
2010 1.8 8.0 6.0 3.0 
2011 2.0 11.0 7.0 3.5 
2012 2.5 14.0 8.0 4.2 
2013 3.0 15.2 9.5 5.0", 
    sep="",header=TRUE) 
y<-ts(as.vector(as.matrix(x)),frequency=4,start=c(2010,1)) 
plot.ts(y) 
time<-seq(as.Date("2010/1/1"),length.out=20,by="3 months") 
axis(1, at = time) 

當我繪製圖形時,我想在x軸中添加日期,爲什麼我的axis(1, at = time)不能在x軸中添加日期數據?當繪製時間序列時將x軸標籤設置爲日期

回答

6

當你打電話給axis(1, at=time)時,你告訴R在time給出的點上用標籤繪製x軸。但是,time是一個字符的矢量,而不是數字。

通常,您可以撥打axis(1, at=..., labels=...)來指示實際標籤以及沿軸放置的位置。在您的情況下,您致電plot.ts隱式設置的x軸限制爲20102013.75,因此您的at參數應反映這些限制。

所以你要調用axis說,標籤是time和位置是2010, 2010.25, 2010.50 ...,就是seq(from=2010, to=2013.25, by=0.25)。一般的解決方案是這樣的:

plot.ts(y,axes=F) # don't plot the axes yet 
axis(2) # plot the y axis 
axis(1, labels=time, at=seq(from=2010, by=0.25, length.out=length(time))) 
box() # and the box around the plot 
相關問題