簡體   English   中英

R中的時間序列圖

[英]time series plot in R

我的數據看起來像這樣:

從1998-01到2013-9,有10,000行代表一個城市和所有月份:

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"

你可以試試

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()

要添加到@ JLLagrange的答案,如果城市太多且顏色難以區分,您可能希望通過facet_grid()傳遞city

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

轉換為時間序列對象之前 ,您能提供一個數據示例,例如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])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM