Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plotting by week with ggplot in R

Tags:

r

ggplot2

I have the following data:

set.seed(123)
timeseq <- as.Date(Sys.time() + cumsum(runif(1000)*86400))
data <- rnorm(1000)
df <- data.frame(timeseq,data)

I wanted to know if anyone has any methods on how to aggregate data by week. What I am attempting to do is plot a time series ggplot, so even better if I can skip this step and have ggplot handle this. Been stuck on this all day.

like image 566
theamateurdataanalyst Avatar asked May 25 '15 04:05

theamateurdataanalyst


2 Answers

Another way to manually aggregate by week using dplyr.

library(dplyr)
df$weeks <- cut(df[,"timeseq"], breaks="week")
agg <- df %>% group_by(weeks) %>% summarise(agg=sum(data))
ggplot(agg, aes(as.Date(weeks), agg)) + geom_point() + scale_x_date() +
    ylab("Aggregated by Week") + xlab("Week") + geom_line()

enter image description here

like image 153
Rorschach Avatar answered Sep 28 '22 19:09

Rorschach


You can also aggregate a date aesthetic with the scale_x_date() function's breaks argument.

ggplot(df, aes(x = timeseq, y = data)) +
    stat_summary(fun.y = sum, geom = "line") +
    scale_x_date(labels = date_format("%Y-%m-%d"),
                 breaks = "1 week")
like image 40
Peter Avatar answered Sep 28 '22 19:09

Peter