假设我有以下数据:
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
然后我融化它:
library(reshape2)
stocks <- melt(stocks, id.vars = "date")
然后将其绘制为累积系列:
library(ggplot2)
ggplot(stocks, aes(date, cumsum(value), color = variable)) + geom_line()
如您所见,由于某种原因,系列的起点具有不同的y值(因此,图表确实从不同的点开始).问题如下:有没有办法让AAPL和LMT系列从同一个(0,0)点开始?
最佳答案 我首先使用dplyr或plyr计算cumsum值:
library(dplyr)
stocks %>%
group_by(variable) %>%
mutate(cumsum = cumsum(value)) %>%
ggplot(., aes(x = date, color = variable)) +
geom_line(aes(y = cumsum))