在R中绘制许多时间序列变量

时间:2014-05-21 09:06:51

标签: r plot ggplot2 time-series

我正在尝试在R中绘制多个时间序列,并且找不到比使用第一列数据创建绘图并手动添加下一个30列的更快的方法:

plot(x = SouthFOX[,1], y = SouthFOX[,2],type="l", xlab = "Year", ylab = "", ylim=c(0,max+10))
lines(x = SouthFOX[,1], y = SouthFOX[,3])
lines(x = SouthFOX[,1], y = SouthFOX[,4])
lines(x = SouthFOX[,1], y = SouthFOX[,5])
lines(x = SouthFOX[,1], y = SouthFOX[,6])
lines(x = SouthFOX[,1], y = SouthFOX[,7])
lines(x = SouthFOX[,1], y = SouthFOX[,8])
lines(x = SouthFOX[,1], y = SouthFOX[,9])
lines(x = SouthFOX[,1], y = SouthFOX[,10])
lines(x = SouthFOX[,1], y = SouthFOX[,11])
lines(x = SouthFOX[,1], y = SouthFOX[,12])
lines(x = SouthFOX[,1], y = SouthFOX[,13])
lines(x = SouthFOX[,1], y = SouthFOX[,14])
lines(x = SouthFOX[,1], y = SouthFOX[,15])
lines(x = SouthFOX[,1], y = SouthFOX[,16])
lines(x = SouthFOX[,1], y = SouthFOX[,17])
lines(x = SouthFOX[,1], y = SouthFOX[,18])
lines(x = SouthFOX[,1], y = SouthFOX[,19])
lines(x = SouthFOX[,1], y = SouthFOX[,20])
lines(x = SouthFOX[,1], y = SouthFOX[,21])
lines(x = SouthFOX[,1], y = SouthFOX[,22])
lines(x = SouthFOX[,1], y = SouthFOX[,23])
lines(x = SouthFOX[,1], y = SouthFOX[,24])
lines(x = SouthFOX[,1], y = SouthFOX[,25])
lines(x = SouthFOX[,1], y = SouthFOX[,26])
lines(x = SouthFOX[,1], y = SouthFOX[,27])
lines(x = SouthFOX[,1], y = SouthFOX[,28])
lines(x = SouthFOX[,1], y = SouthFOX[,29])
lines(x = SouthFOX[,1], y = SouthFOX[,30])

我的数据是一个30列的data.frame,第一列作为Year,接下来的29作为给定样本的每年测量值:

> head(SouthFOX)
  Year  X050229  X050247
1 2005       NA       NA
2 2004 21.34867 16.46167
3 2003 23.89700 19.67367
4 2002 19.17867 16.91817
5 2001 31.69717 21.58650
6 2000 29.51600 20.72450

我想要的图表看起来像this

理想情况下,我想使用ggplot2,但这似乎不起作用。 提前致谢

2 个答案:

答案 0 :(得分:1)

对于base-r,您可以使用matplot

mat <- matrix(runif(1000), ncol = 10)
df <- data.frame(year = 1:100, mat)

matplot(df$year, df[ ,-1], type = 'l')

enter image description here

对于ggplot,您需要将数据重组为长格式(例如使用reshape2::melt()

require(ggplot2)
require(reshape2)
dfm <- melt(df, id.vars = 'year')
ggplot(dfm, aes(x = year, y = value, color = variable)) +
  geom_line()

enter image description here

答案 1 :(得分:0)

autoplot.zoo尝试zoo package。 (要在单独的面板中查看每个系列,请省略facets=NULL。)

DF <- data.frame(year = 1:25, a = 1:25, b = 25:1) # test data

library(zoo)
library(ggplot2)

z <- read.zoo(DF, FUN = identity)
autoplot(z, facets = NULL)

screenshot