2013-02-24 271 views
1

我一直在想如何将ts对象转换为data.frame,以便我可以将它绘制在ggplot中。任何人有一些伟大的想法如何做到这一点?这里的ts对象看起来像将TS对象转换为data.frame对象

> austres 
     Qtr1 Qtr2 Qtr3 Qtr4 
1971   13067.3 13130.5 13198.4 
1972 13254.2 13303.7 13353.9 13409.3 
1973 13459.2 13504.5 13552.6 13614.3 
1974 13669.5 13722.6 13772.1 13832.0 
1975 13862.6 13893.0 13926.8 13968.9 
1976 14004.7 14033.1 14066.0 14110.1 
1977 14155.6 14192.2 14231.7 14281.5 
1978 14330.3 14359.3 14396.6 14430.8 
1979 14478.4 14515.7 14554.9 14602.5 
1980 14646.4 14695.4 14746.6 14807.4 
1981 14874.4 14923.3 14988.7 15054.1 
1982 15121.7 15184.2 15239.3 15288.9 
1983 15346.2 15393.5 15439.0 15483.5 
1984 15531.5 15579.4 15628.5 15677.3 
1985 15736.7 15788.3 15839.7 15900.6 
1986 15961.5 16018.3 16076.9 16139.0 
1987 16203.0 16263.3 16327.9 16398.9 
1988 16478.3 16538.2 16621.6 16697.0 
1989 16777.2 16833.1 16891.6 16956.8 
1990 17026.3 17085.4 17106.9 17169.4 
1991 17239.4 17292.0 17354.2 17414.2 
1992 17447.3 17482.6 17526.0 17568.7 
1993 17627.1 17661.5    
+0

看一看http://stackoverflow.com/问题/ 5331901 /转换在数据框架和背面 – alexwhan 2013-02-24 08:01:49

回答

2

这里的一种方式。这个想法是以长格式重塑你的时间系列。这里我使用reshape2来融化数据。

创建我的时间序列,注意,这里

dat <- ts(rnorm(12*5, 17, 8), start=c(1981,1), frequency = 4) 

频率比我把我的数据在长格式

library(reshape2) 
library(zoo) 
dat.m <- data.frame(yr=index(dat),value=melt(dat)$value) 

我绘制的结果:

library(ggplot2) 
qplot(x=yr,y=value,data=dat.m,geom='line') 

enter image description here

+0

我想使用此解决方案。但这只是不起作用。 Data.frame(yr = index(dat),value = melt(dat)$ value)中的错误: 找不到函数“index” – tagoma 2014-02-27 16:05:46

+0

@edouard谢谢我添加了'zoo'包。 – agstudy 2014-02-27 16:13:33

+0

thx。我试图用时间()替换索引()并得到了一些结果 – tagoma 2014-02-27 16:24:14

1

没有为GGPLOT2的autoplot功能的动物园方法:

# first create some sample data 
library(ggplot2) 
library(zoo) 
tt <- ts(rnorm(100), freq = 4, start = c(1971, 2)) # sample data 

# convert to zoo and plot 
z <- as.zoo(tt) 
autoplot(z) 

还是有点票友(如下图所示):

autoplot(z) + 
    geom_vline(xintercept = time(z)[cycle(z) == 1], col = "grey", alpha = .7) 

enter image description here

+0

谢谢你们俩。这两种解决方案都很好。 – user2103970 2013-02-28 01:59:10