与 2 cumul ggplot 同源

Same origin with 2 cumul ggplot

当我在同一张图中绘制 2 个数据框时,无法获得相同的原点 这是我的数据样本:

spec_sum <- data.frame(x = c("2015-01-08","2015-01-13","2015-01-14","2015-01-15","2015-01-15","2015-01-19","2015-01-19","2015-01-21","2015-01-21","2015-01-27"),y = c(1, 1, 1, -1, -1, 1, 1, 1, 1, 1))

odtgen_sum <- data.frame(x = c("2015-01-12","2015-01-14","2015-01-15","2015-01-26","2015-01-27","2015-01-29","2015-01-30","2015-01-30","2015-02-04","2015-02-04"),y=c(1,-1,1,1,1,1,-1,-1,-1,1))

这是我的 ggplot 代码:

library(reshape)
newData <- melt(list(spec_sum = spec_sum, odtgen_sum = odtgen_sum),  
  id.vars = "x")

#Specify colour vector
cols <- c("blue", "red", "green", "orange")

ggplot(newData, aes(x, cumsum(value), colour = L1)) + 
  geom_line() +  xlab("Date") + ylab("Nb depeches dev") +
  scale_colour_manual(values = cols) + theme_bw() +
  theme(legend.justification=c(0,0), legend.position=c(0.8,0))

sample

我猜**这是因为 cumsum 在您的示例中没有按组汇总。尝试预先计算它:

# create toy data
set.seed(1123)
n <- 100
df <- data.frame(f=gl(2, n, lab=letters[1:2]), 
                 x=rep(1:n, 2), 
                 y=rbinom(2*n, 1, .5))
# add cumulative sum
df$y_cum <- ave(df$y, df$f, FUN=cumsum)
# plot
ggplot(df, aes(x, y_cum, color=f)) + geom_line()

** 您没有提供可重现的示例。