0

我的数据看起来像这样:

有 10,000 行,每行代表一个城市和自 1998-01 到 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"
4

3 回答 3

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()
于 2013-10-31T22:03:10.067 回答
1

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

ggplot(forecl, aes(x = month, y = value, color = city, group = city)) +
  geom_line() +
  facet_grid( ~ city)
于 2013-10-31T23:35:55.157 回答
0

您能否提供一个数据示例,例如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])
于 2013-10-31T22:31:54.937 回答