首页 文章

Barplot与堆积的时间序列

提问于
浏览
0

我有一些月度时间序列,可以求和(通常是权重,但在这里不重要)来获得索引的值 .

这是我的数据的摘录:

01.2009  02.2009  03.2009  04.2009  05.2009  06.2009  07.2009
aaa 321.5743 323.7106 323.9933 326.1296 329.6482 328.3287 328.9571
bbb 322.0770 324.4646 324.8730 327.1978 331.2504 329.3969 330.0252
ccc 324.7473 326.7894 328.0146 329.2398 330.4964 331.3447 332.1929

我正在学习使用 ggplot2 和我'd like to get a stacked barplot plot, i.e. at each point of time on the horizontal axis, there'这是一个三色条,其值为 aaa+bbb+ccc ,因此它代表了每个系列索引的时间演变贡献 .

我还生成了一个类型的矢量 dates

"2009-01-15" "2009-02-15" "2009-03-15"

这是我到现在为止所尝试的

plot.data <- melt(as.data.frame(cbind(t(data), dates)), id.vars="dates")
ggplot(plot.data, aes(x=factor(dates), y=value)) + geom_bar(stat="identity")

但是,这似乎使用时间序列名称,例如, aaa ,作为一个额外的因素,所以我只是做错了 . 任何人都可以帮我这个吗?

1 回答

  • 1

    为了使用ggplot2,您应该将数据放在长格式中,但之前需要将rownames作为新列添加 . 此列将用于堆叠每个日期的条形图 .

    在这里我的代码

    ## read data
    dat <- read.table(text='   01.2009  02.2009  03.2009  04.2009  05.2009  06.2009  07.2009
    aaa 321.5743 323.7106 323.9933 326.1296 329.6482 328.3287 328.9571
    bbb 322.0770 324.4646 324.8730 327.1978 331.2504 329.3969 330.0252
    ccc 324.7473 326.7894 328.0146 329.2398 330.4964 331.3447 332.1929')
    ## add rownames as index column and put data in long format
    dat.m <- melt(cbind(index=rownames(dat),dat))
    ## convert variable to a valid date to get pretty axes
    dat.m$variable <- as.Date(paste0('15.',gsub('X','',dat.m$variable)),format='%d.%m.%Y')
    
    library(ggplot2)
    ## plot it!
    ggplot(dat.m) +
      geom_bar(aes(x=variable,y=value,fill=index),
               stat='identity')
    

    enter image description here

相关问题