【问题标题】:time series plot in RR中的时间序列图
【发布时间】:2013-11-03 23:39:17
【问题描述】:

我的数据如下所示:

有 10,000 行,每行代表一个城市和自 1998 年 1 月至 2013 年 9 月以来的所有月份:

RegionName| State|  Metro|         CountyName|  1998-01|      1998-02|  1998-03

New York|   NY| New York|   Queens|         1.3414|   1.344|             1.3514

Los Angeles|    CA| Los Angeles|    Los Angeles|    12.8841|     12.5466|   12.2737

Philadelphia|   PA| Philadelphia|   Philadelphia|   1.626|    0.5639|   0.2414

Phoenix|            AZ| Phoenix|            Maricopa|    2.7046|       2.5525|  2.3472

我希望能够为任何城市或多个城市绘制自 1998 年以来所有月份的图。

我试过这个,但我得到一个错误。我不确定我是否在尝试这个权利。任何帮助将不胜感激。谢谢你。

forecl <- ts(forecl, start=c(1998, 1), end=c(2013, 9), frequency=12)

plot(forecl)

Error in plots(x = x, y = y, plot.type = plot.type, xy.labels = xy.labels,  : 
  cannot plot more than 10 series as "multiple"

【问题讨论】:

  • 如果数据从 2005 年开始,为什么要从 1998 年开始?你应该发帖dput(head(forecl))。您还应该指定绘图的设计。所有年份和月份都按顺序排列,还是所有 1 月至 12 月都堆叠?如果你改成长格式可能会更好。

标签: r time-series


【解决方案1】:

你可以试试

require(reshape)
require(ggplot2)
forecl <- melt(forecl, id.vars = c("region","state","city"), variable_name = "month")
forecl$month <- as.Date(forecl$month)
ggplot(forecl, aes(x = month, y = value, color = city)) + geom_line()

【讨论】:

  • 感谢您的回复。我试过 forecl$month
  • 啊,抱歉,没有注意到您的日期是 %Y-%m 格式。尝试关注this example 并使用 forecl$month
【解决方案2】:

要添加到@JLLagrange 的答案,如果城市太多且颜色难以区分,您可能希望通过facet_grid() 传递city

ggplot(forecl, aes(x = month, y = value, color = city, group = city)) +
  geom_line() +
  facet_grid( ~ city)

【讨论】:

  • 好建议——有 10000 行,得到一个二维网格甚至可能是有意义的,比如 facet_grid(state ~ metro),
【解决方案3】:

您能否提供一个数据示例,例如dput(head(forecl))转换为时间序列对象之前?问题也可能与ts 对象有关。

无论如何,我认为有两个问题。

首先,数据是宽格式的。我不确定您的列名,因为它们应该以字母开头,但无论如何,一般的想法是这样的:

test <- structure(list(
  city = structure(1:2, .Label = c("New York", "Philly"), 
  class = "factor"), state = structure(1:2, .Label = c("NY", 
  "PA"), class = "factor"), a2005.1 = c(1, 1), a2005.2 = c(2, 5
  )), .Names = c("city", "state", "a2005.1", "a2005.2"), row.names = c(NA, 
  -2L), class = "data.frame")

test.long <- reshape(test, varying=c(3:4), direction="long")

其次,我认为您试图同时绘制太多城市。试试:

plot(forecl[, 1])

plot(forecl[, 1:5])

【讨论】:

  • 我编辑了我的帖子以包含真实的列名和几行; R 读取所有以字符开头的列名;谢谢你的帮助