簡體   English   中英

如何使用ggplot2按時間段為R中的時間序列圖聚合變量

[英]How to aggregate variable by time period for time series plot in R using 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)) + geom_point(shape = 1) # Not right

我最終希望它生成如下圖:

count<- table(frame$year, frame$y)[,2]
plot(2000:2005, count, type = "l")

在此處輸入圖片說明

我是ggplot ,任何指針將不勝感激。 謝謝。

實際上,您的程序中缺少一行。 您需要一個返回年份的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

嘗試:

library(ggplot2)
library(dplyr)
frame %>% group_by(year) %>% summarise(sum = sum(y)) %>% 
ggplot(aes(x = year, y = sum)) + geom_line()

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM