2014-10-20 150 views
-3

我有一個包含多個時間序列的xts對象。數據是這樣的:使用ggplot繪製多個時間序列R

頭(數據)

date   v1   v2   v3   v4   v5   v6 
2014-07-31   NA   721  696   NA   487   469 
2014-08-02  735   752  696  559   505   469 
2014-08-04  1502   737  696  757   510   469 
2014-08-06  799   722  697  559   487   469 
    ... 

「日期」是一個日期變量和其他變量包含價格的發展。我想自動繪製所有系列(如v1,v2,v3),而無需手動插入其名稱。這可以使用xtsExtra完成,但是此包不再適用於R3.1.0。

有沒有辦法使用ggplot2在一個窗口中繪製這些時間序列? (含標籤和不同顏色)

非常感謝!

+0

[重複的例子(http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) – shekeine 2014-10-20 17:10:24

+0

可以提供此鏈接上的答案將有助於http://stackoverflow.com/questions/18801556/multiple-time-series-in-one-plot – Meso 2014-10-20 17:16:05

回答

2

您可以使用group參數繪製多行系列ggplot。從原始數據框中,您可能需要使用reshape2軟件包中的melt重新格式化。

library(ggplot2) 
library(reshape2) 
df<-data.frame(date=as.Date(c('2014-06-25','2014-06-26','2014-06-27')),v1=rnorm(3),v2=rnorm(3)) 
newdf<-melt(df,'date') 
ggplot(newdf,aes(x=date,y=value,group=variable,color=variable)) + geom_line() +scale_x_date() 
+0

非常感謝!那工作 – 2014-10-20 21:09:08