如何使用ggplot2为R中的时间序列图按时段聚合变量

如何使用ggplot2为R中的时间序列图按时段聚合变量,r,ggplot2,R,Ggplot2,我想使用ggplot2创建一个时间序列图,其中变量随时间绘制。但是,对于每个时间段,我想绘制该时间段的累积计数。例如: set.seed(123) frame <- data.frame(id = sort(rep(c(0:5), 5)),year = rep(c(2000:2005), 5), y = sample(0:1,30, replace = TRUE)) table(frame$year, frame$y) ggplot(frame, aes(x = year, y = y))

我想使用
ggplot2
创建一个时间序列图,其中变量随时间绘制。但是,对于每个时间段,我想绘制该时间段的累积计数。例如:

set.seed(123)
frame <- data.frame(id = sort(rep(c(0:5), 5)),year = rep(c(2000:2005), 5), y = sample(0:1,30, replace = TRUE))
table(frame$year, frame$y)
ggplot(frame, aes(x = year, y = y)) + geom_point(shape = 1) # Not right
set.seed(123)

frame您的程序实际上缺少一行。您需要一个数据框,返回该年y变量的总和

set.seed(123) frame <- data.frame(id = sort(rep(c(0:5), 5)),year = rep(c(2000:2005), 5), y = sample(0:1,30, replace = TRUE)) table(frame$year, frame$y) newFrame <-aggregate(frame$y, list(frame$year),sum) ggplot(frame, aes(x = newFrame$Group.1, y = newFrame$x)) + geom_point(shape = 1) # Better 种子集(123) 帧尝试:


您的预期输出是什么 set.seed(123) frame <- data.frame(id = sort(rep(c(0:5), 5)),year = rep(c(2000:2005), 5), y = sample(0:1,30, replace = TRUE)) table(frame$year, frame$y) newFrame <-aggregate(frame$y, list(frame$year),sum) ggplot(frame, aes(x = newFrame$Group.1, y = newFrame$x)) + geom_point(shape = 1) # Better
library(ggplot2)
library(dplyr)
frame %>% group_by(year) %>% summarise(sum = sum(y)) %>% 
ggplot(aes(x = year, y = sum)) + geom_line()