1. 程式人生 > >R語言-時間序列圖

R語言-時間序列圖

1.時間序列圖

plot()函式

> air<-read.csv("openair.csv") 
> plot(air$nox~as.Date(air$date,"%d/%m/%Y %H:%M"),  #把年月日時分秒轉換成日期格式
+ type="l", 
+ xlab="Time", ylab="Concentration (ppb)", 
+ main="Time trend of Oxides of Nitrogen") 

zoo()包

> library(zoo) 
> plot(zoo(air$nox,as.Date(air$date,"%d/%m/%Y %H:%M")),   #zoo簡化plot函式的引數設定
+ xlab="Time", ylab="Concentration (ppb)", 
+ main="Time trend of Oxides of Nitrogen") 

2.時間刻度可讀化 

> plot(air$nox~as.Date(air$date,"%d/%m/%Y %H:%M"),type="l", 
+ xaxt="n",                                #不畫X軸
+ xlab="Time", ylab="Concentration (ppb)", 
+ main="Time trend of Oxides of Nitrogen") 
> xlabels<-strptime(air$date, format = "%d/%m/%Y %H:%M") 
> axis.Date(1,                            #設定X軸刻度顯示位置
+ at=xlabels[xlabels$mday==1], #設定刻度為每天一個刻度
+ format="%b-%Y") #設定標記格式

3.標記特定的時間事件 

> plot(air$nox~as.Date(air$date,"%d/%m/%Y %H:%M"),type="l", 
+ xlab="Time", ylab="Concentration (ppb)", 
+ main="Time trend of Oxides of Nitrogen") 
> abline(v=as.Date("25/12/2003","%d/%m/%Y"),col="red")    #在特定時間畫垂直線

 

示例:股票資料圖

> library(quantmod) 
> library(tseries) 
> aapl<-get.hist.quote(instrument = "aapl", quote = c("Cl", "Vol"))        #抓取蘋果股票資料
> goog <- get.hist.quote(instrument = "goog", quote = c("Cl", "Vol"))      #抓取谷歌股票資料
> msft <- get.hist.quote(instrument = "msft", quote = c("Cl", "Vol"))      #抓取微軟股票資料
> plot(msft$Close,main = "Stock Price Comparison", 
+ ylim=c(0,800), col="red", type="l", lwd=0.5, 
+ pch=19,cex=0.6, xlab="Date" ,ylab="Stock Price (USD)") 
> lines(goog$Close,col="blue",lwd=0.5) 
> lines(aapl$Close,col="gray",lwd=0.5) 
> legend("top",horiz=T,legend=c("Microsoft","Google","Apple"),             #horiz=T圖例水平擺開 
+ col=c("red","blue","gray"),lty=1,bty="n")

> getSymbols("AAPL",src="yahoo") 
> barChart(AAPL)                       #畫成交量與股價圖
> candleChart(AAPL,theme="white")      #畫蠟燭圖