首页 文章

R中的时间序列与ggplot2

提问于
浏览
3

我是一个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("")

但是,是否可以从第一个对象生成时间序列图,其中列表示年份 .

2 回答

  • 4

    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 等的详细信息 .

  • 3

    我猜这个“时间序列图”你的意思是你想得到一个条形图而不是折线图?

    在这种情况下,您必须稍微修改代码才能将正确的参数传递给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("")
    

    这会产生以下条形图:

    enter image description here

相关问题