将多个时间序列数据(长格式)绘制成一个图?

时间:2013-05-27 15:24:10

标签: r plot zoo

假设我有3个时间序列数据“a”,“b”,“c”,每个数据都有2个变量要在7天内记录。

以下是示例代码:

require(data.table)  
#Create data
DT<-data.table(type=c(rep("a",7),rep("b",7),rep("c",7)), time=1:7,V1=rnorm(7*3,10,5),V2=rnorm(7*3,100,20),key="type")
# plot.zoo
require(zoo)
plot(zoo(DT["a"])[,3:4])

enter image description here

我能够一次绘制一种类型(如上所述),但我想将所有“a”“b”“c”...绘制到该面板中,其中不同的颜色代表不同类型的时间序列。 / p>

所以我要找的是一个有两个面板(“V1”和“V2”)的情节,在每个面板中,有几行(“a”,“b”,“c”.. 。)用不同的颜色

2 个答案:

答案 0 :(得分:2)

例如,使用lattice包,您可以这样做:

library(lattice)
xyplot(V1+V2~time,groups=type,data=DT,type='l')

enter image description here

您也可以使用ggplot2

执行此操作
library(reshape2)
dt.m <- melt(DT,measure.vars=c('V1','V2'))

ggplot(dt.m) +
 geom_line(aes(x=time,y=value,group=type,color=type)) +
  facet_grid(~variable)

enter image description here

答案 1 :(得分:2)

尝试使用动物园经典图形,动物园格子图形和动物园ggplot2图形:

library(zoo)
z <- read.zoo(DT, split = 1, index = 2, FUN = identity)
Names <- read.table(text = names(z), sep = ".", col.names = c("screen", "col"))

plot(z, screen = Names$screen, col = Names$col) # also see note 3 below

library(lattice)
xyplot(z, screen = Names$screen, col = Names$col) # also see note 3 below


library(ggplot2) # also see note 4 below
m <- fortify(z, melt = TRUE)
m2 <- transform(m, screen = sub("\\..*", "", Series), col = sub(".*\\.", "", Series))
qplot(Index, Value, data = m2, col = col, geom = "line") + facet_wrap(~ screen)

备注

1)如果我们只想要单独的面板,那就是plot(z)xyplot(z)autoplot(z)

2)names(z)Names是:

> names(z)
[1] "V1.a" "V2.a" "V1.b" "V2.b" "V1.c" "V2.c"
> Names
  screen col
1     V1   a
2     V2   a
3     V1   b
4     V2   b
5     V1   c
6     V2   c

3)我们可以将其硬编码为此(在这种情况下我们不需要Names):

plot(z, screen = 1:2, col = c(1, 1, 2, 2, 3, 3))

xyplot(z, screen = 1:2, col = c(1, 1, 2, 2, 3, 3))

4)这是一个不涉及z的ggplot2替代方案。它使用data.table包将DT转换为长格式,然后执行qplot

long <- DT[, list(Series = names(.SD), Value = unlist(.SD)), by = list(type, time)]
qplot(time, Value, data = long, col = type, geom = "line") + facet_wrap(~ Series)