r - 从同一点开始多个累积系列

标签 r ggplot2

假设我有以下数据:

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")

看起来像这样:
         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

然后我melt它:
library(reshape2)
stocks <- melt(stocks, id.vars = "date")

然后将其绘制为累积系列:
library(ggplot2)
ggplot(stocks, aes(date, cumsum(value), color = variable)) + geom_line()

example plot

如你所见,系列的起点因某种原因不同y值(因此,图表确实从不同的点开始)。问题如下:有没有办法让AAPLLMT系列从相同的 (0,0) 点开始?

最佳答案

我会计算 cumsum首先使用 dplyr 的值或 plyr :

library(dplyr)

stocks %>%
  group_by(variable) %>%
  mutate(cumsum = cumsum(value)) %>%
  ggplot(., aes(x = date, color = variable)) +
    geom_line(aes(y = cumsum))

关于r - 从同一点开始多个累积系列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30441406/

相关文章:

r - 创建长度为 n 的二进制向量的 0,1 或 2 "1"s 的所有可能组合

r - 使用 R 操作 Excel 电子表格数据并将输出返回到单独的工作表

r - GGplot - 基于其他列的同一列值的多行 - 无方面

r - 转置相同的对象

R包开发-函数别名

r - 在 rstan 中指定矩阵的先验分布

r - 如何为面添加不同的线

r - 为ggplot创建注释函数所需的方法

r - 使用 ggplot2 绘制分位数

仅当用户选择按钮时渲染绘图