使用ggplot R绘制多个时间序列

时间:2014-10-20 17:06:51

标签: r ggplot2 time-series xts

我有一个包含许多时间序列的xts对象。数据如下:

头(数据)

   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
    ...

“date”是日期变量,其他变量包含价格发展。我想自动绘制所有系列(所以v1,v2,v3),而无需手动插入其名称。这可以使用xtsExtra完成,但R3.1.0不再提供此软件包。

有没有办法使用ggplot2在一个窗口中绘制这些时间序列? (包括标签和不同颜色)

非常感谢!

1 个答案:

答案 0 :(得分:2)

您可以使用group参数为ggplot绘制多个线系列。在原始数据框架中,您可能需要使用melt包中的reshape2重新格式化内容。

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()
相关问题