cumulative plot using ggplot2

后端 未结 3 1292
梦如初夏
梦如初夏 2020-12-15 23:38

I\'m learning to use ggplot2 and am looking for the smallest ggplot2 code that reproduces the base::plot result below. I\'ve tried a f

相关标签:
3条回答
  • 2020-12-16 00:03

    Try this:

    ggplot(df, aes(x=1:5, y=cumsum(val))) + geom_line() + geom_point()
    

    enter image description here

    Just remove geom_point() if you don't want it.

    Edit: Since you require to plot the data as such with x labels are dates, you can plot with x=1:5 and use scale_x_discrete to set labels a new data.frame. Taking df:

    ggplot(data = df, aes(x = 1:5, y = cumsum(val))) + geom_line() + 
            geom_point() + theme(axis.text.x = element_text(angle=90, hjust = 1)) + 
            scale_x_discrete(labels = df$date) + xlab("Date")
    

    enter image description here

    Since you say you'll have more than 1 val for "date", you can aggregate them first using plyr, for example.

    require(plyr)
    dd <- ddply(df, .(date), summarise, val = sum(val))
    

    Then you can proceed with the same command by replacing x = 1:5 with x = seq_len(nrow(dd)).

    0 讨论(0)
  • Jan Boyer seems to have found a more concise solution to this problem in this question, which I have shortened a bit and combined with the answers of Prradep, so as to provide a (hopefully) up-to-date-answer:

    ggplot(data = df, 
       aes(x=date)) +
    geom_col(aes(y=value)) +
    geom_line(aes(x = date, y = cumsum((value))/5, group = 1), inherit.aes = FALSE) +
    ylab("Value") + 
    theme(axis.text.x = element_text(angle=90, hjust = 1))
    

    Note that date is not in Date-Format, but character, and that value is already grouped as suggested by Prradep in his answer above.

    0 讨论(0)
  • 2020-12-16 00:08

    After a couple of years, I've settled on doing:

    ggplot(df, aes(as.Date(as.character(date), '%Y%m%d'), cumsum(val))) + geom_line()
    
    0 讨论(0)
提交回复
热议问题