2013-02-24 368 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