【问题标题】:Time Series in R with ggplot2R中的时间序列与ggplot2
【发布时间】:2011-02-11 19:10:29
【问题描述】:

我是 ggplot2 新手,有一个关于时间序列图的相当简单的问题。

我有一个数据集,其中数据的结构如下。

      Area 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007
  MIDWEST   10    6   13   14   12    8   10   10    6    9

当数据以这种格式结构化时,我如何生成时间序列。

使用 reshape 包,我可以将数据更改为如下所示:

totmidc <- melt(totmidb, id="Area")
totmidc

    Area    variable  value
1  MIDWEST     1998    10
2  MIDWEST     1999     6
3  MIDWEST     2000    13
4  MIDWEST     2001    14
5  MIDWEST     2002    12
6  MIDWEST     2003     8
7  MIDWEST     2004    10
8  MIDWEST     2005    10
9  MIDWEST     2006     6
10 MIDWEST     2007     9

然后运行以下代码得到想要的绘图。

ggplot(totmidc, aes(Variable, Value)) + geom_line() + xlab("") + ylab("")

但是,是否可以从第一个生成时间序列图? 列代表年份的对象。

【问题讨论】:

    标签: r plot ggplot2 time-series


    【解决方案1】:

    ggplot2 给你的错误是什么?以下似乎适用于我的机器:

    Area <-  as.numeric(unlist(strsplit("1998 1999 2000 2001 2002 2003 2004 2005 2006 2007", "\\s+")))
    MIDWEST <-as.numeric(unlist(strsplit("10    6   13   14   12    8   10   10    6    9", "\\s+")))
    
    qplot(Area, MIDWEST, geom = "line") + xlab("") + ylab("")
    
    #Or in a dataframe
    
    df <- data.frame(Area, MIDWEST)
    qplot(Area, MIDWEST, data = df, geom = "line") + xlab("") + ylab("")
    

    您可能还想查看ggplot2 网站以了解有关scale_date 等的详细信息。

    【讨论】:

      【解决方案2】:

      我猜“时间序列图”是指你想要一个条形图而不是折线图?

      在这种情况下,您只需稍微修改代码即可将正确的参数传递给 geom_bar()。 geom_bar 默认统计是 stat_bin,它将计算您的类别在 x 尺度上的频率计数。使用您的数据,您希望覆盖此行为并使用 stat_identity。

      library(ggplot2)
      
      # Recreate data
      totmidc <- data.frame(
              Area = rep("MIDWEST", 10),
              variable = 1998:2007,
              value = round(runif(10)*10+1)
      )
      
      # Line plot
      ggplot(totmidc, aes(variable, value)) + geom_line() + xlab("") + ylab("")
      
      # Bar plot
      # Note that the parameter stat="identity" passed to geom_bar()
      ggplot(totmidc, aes(x=variable, y=value)) + geom_bar(stat="identity") + xlab("") + ylab("")
      

      这会产生以下条形图:

      【讨论】:

      • 感谢您的建议,但我希望用一条线连接数据点。使用条形图在多个时间点可视化数据的问题在于,它可能导致“过量的炭墨”(Verzani,2005,p.35)
      • 应该是“图表墨水过多”……无论如何,问题解决了。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-30
      • 2021-03-17
      • 1970-01-01
      • 2012-01-29
      • 2013-02-12
      • 1970-01-01
      相关资源
      最近更新 更多