Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Start multiple cumulative series from the same point

Tags:

r

ggplot2

Let's say I have the following data:

stocks <- structure(list(date = structure(c(15120, 15126, 15156, 15187, 
15218, 15250, 15279, 15309, 15342, 15371), class = "Date"), AAPL = c(0, 
-0.0349594915528398, 0.163285209696362, -0.0144692603838991, 
-0.00912094189637977, 0.0615229895783601, -0.0557834027614259, 
0.0596546102691159, 0.127111450820476, 0.188310389721697), LMT = c(0, 
0.0394093623514219, -0.064715298915223, -0.0103142125320749, 
-0.0208923278478336, 0.0448787708206146, 0.0430164493053814, 
0.035188599184363, 0.0175524826908838, 0.0861273642597269)), .Names = c("date", 
"AAPL", "LMT"), row.names = c(NA, 10L), class = "data.frame")

Which looks something like that:

         date         AAPL         LMT
1  2011-05-26  0.000000000  0.00000000
2  2011-06-01 -0.034959492  0.03940936
3  2011-07-01  0.163285210 -0.06471530
4  2011-08-01 -0.014469260 -0.01031421
5  2011-09-01 -0.009120942 -0.02089233
6  2011-10-03  0.061522990  0.04487877
7  2011-11-01 -0.055783403  0.04301645
8  2011-12-01  0.059654610  0.03518860
9  2012-01-03  0.127111451  0.01755248
10 2012-02-01  0.188310390  0.08612736

Then I melt it:

library(reshape2)
stocks <- melt(stocks, id.vars = "date")

And then plot it as the cumulative series:

library(ggplot2)
ggplot(stocks, aes(date, cumsum(value), color = variable)) + geom_line()

example plot

As you see, the starting points of the series for some reason have different y values (and thus, the graphs do start from different points). The question would be the following: is there any way to make both AAPL and LMT series start from the same (0,0) point?

like image 960
A S Avatar asked Oct 20 '22 11:10

A S


1 Answers

I would calculate the cumsum value first using dplyr or plyr:

library(dplyr)

stocks %>%
  group_by(variable) %>%
  mutate(cumsum = cumsum(value)) %>%
  ggplot(., aes(x = date, color = variable)) +
    geom_line(aes(y = cumsum))
like image 67
JasonAizkalns Avatar answered Oct 22 '22 00:10

JasonAizkalns