使用ggplot绘制每日数据的问题

时间:2012-11-12 09:50:21

标签: r ggplot2

我试图在ggplot中绘制9个变量的每日数据,但是我得到的图表无法正确处理日期变量。 x轴不可读,无法读取图表。我猜测处理日期存在问题。

这是数据: https://dl.dropbox.com/u/22681355/su.csv

以下是我一直在使用的代码:

su=read.csv(file="su.csv", head=TRUE)

meltdf=melt(su)

ggplot(meltdf, aes(x=Date, y=value, colour=variable, group=variable))+geom_line()

这是输出:

https://dl.dropbox.com/u/22681355/output.jpg

这是在excel中完成的相同情节,为什么它看起来完全不同?

1 个答案:

答案 0 :(得分:1)

现在Date是一个因素,而不是真正的R日期对象。您可以使用strptime将字符串解析为POSIXct对象。这将产生更好的结果。


与您的问题没有直接关系,但另外您可以使用facet_wrap拆分时间序列并将它们叠加在一起。我写了一个小函数来计算facet_wrap所需的指数:

createTimeseriesCutupIdx = function(ncuts, nrows, labels) {
  if(missing(labels)) labels = LETTERS[1:ncuts]
  pointsPerCutup = floor((1/ncuts) * nrows)
  idx = rep(labels, each = pointsPerCutup)
  if(length(idx) < nrows) {
    idx[(length(idx) + 1):nrows] <- idx[length(idx)]
  }   
  return(idx)
}

以及如何使用它的示例:

require(ggplot2); theme_set(theme_bw())
tserie_length = 5000
df = data.frame(t = as.POSIXct("2006-01-01") + (1:tserie_length) * 3600, 
                value = runif(tserie_length))
ggplot(df, aes(x = t, y = value)) + geom_line()

enter image description here

df$idx = createTimeseriesCutupIdx(ncuts = 5, nrows = nrow(df))
ggplot(df, aes(x = t, y = value)) + 
   geom_line() + 
   facet_wrap(~ idx, scales = "free_x", ncol = 1)

enter image description here

这样就可以以有意义的方式绘制更大的时间序列。

相关问题