【问题标题】:Issue with plotting daily data using ggplot使用 ggplot 绘制每日数据的问题
【发布时间】:2012-11-12 09:50:20
【问题描述】:

我试图在 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 中绘制的相同图,为什么看起来完全不同?

【问题讨论】:

  • 请定义not properly,现在很明显你的问题是什么。另外,您的pdf很大,请保存为png之类的图片格式。

标签: r ggplot2


【解决方案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()

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)

这使得以有意义的方式绘制更大的时间序列成为可能。

【讨论】:

  • 这是用excel做的图,为什么看起来完全不同? dl.dropbox.com/u/22681355/su.tiff
  • 可能是因为我上面使用的数据不是你的数据,而是我在答案中生成的随机数据集。
  • 这是我得到的错误:> su$Date=strptime(su$Date, format="%Y-%m-%d") $&lt;-.data.frame(*tmp*, " Date", value = list(sec = numeric(0), : 替换有 0 行,数据有 4787
  • 你的格式参数不好,导致NA的。仔细阅读strptime的文档,构造正确的格式。例如,您将%Y(四位数的年份)列为您的第一个格式条目。但是,这是最后一个条目。
猜你喜欢
  • 2021-12-16
  • 2017-05-26
  • 2020-11-25
  • 1970-01-01
  • 1970-01-01
  • 2019-09-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多