【问题标题】:Barplot with stacked time series具有堆叠时间序列的条形图
【发布时间】:2013-10-06 22:07:46
【问题描述】:

我有许多月度时间序列,可以将它们相加(通常带有权重,但在这里并不重要)以获得索引值。

这是我的数据的摘录:

    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,我想得到一个堆积条形图,即在水平轴上的每个时间点,都有一个三色条,其值为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,作为一个额外的因素,所以我没有堆叠任何东西。我确定我只是做错了什么。谁能帮我解决这个问题?

【问题讨论】:

    标签: r ggplot2 time-series


    【解决方案1】:

    为了使用 ggplot2,你应该把你的数据放在长格式中,但你需要先添加行名作为新列。此列将用于堆叠每个日期的条形图。

    这是我的代码

    ## 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')
    

    【讨论】:

    • 太棒了。我已经为此奋斗了几个小时了。谢谢!
    猜你喜欢
    • 2019-01-03
    • 2012-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多