Create a gist now

Instantly share code, notes, and snippets.

Plot Weekly or Monthly Totals in R
# load data:
log <- data.frame(Date = c("2013/05/25","2013/05/28","2013/05/31","2013/06/01","2013/06/02","2013/06/05","2013/06/07"),
Quantity = c(9,1,15,4,5,17,18))
# convert date variable from factor to date format:
log$Date <- as.Date(log$Date,
"%Y/%m/%d") # tabulate all the options here
# create variables of the week and month of each observation:
log$Month <- as.Date(cut(log$Date,
breaks = "month"))
log$Week <- as.Date(cut(log$Date,
breaks = "week",
start.on.monday = FALSE)) # changes weekly break point to Sunday
# graph by month:
ggplot(data = log,
aes(Month, Quantity)) +
stat_summary(fun.y = sum, # adds up all observations for the month
geom = "bar") + # or "line"
labels = date_format("%Y-%m"),
breaks = "1 month") # custom x-axis labels
# graph by week:
ggplot(data = log,
aes(Week, Quantity)) +
stat_summary(fun.y = sum, # adds up all observations for the week
geom = "bar") + # or "line"
labels = date_format("%Y-%m-%d"),
breaks = "1 week") # custom x-axis labels

nice (and timely) for something I'm doing. thx.


Excellent cut function example!


awesome stuff. Was helpful in helping me understand the scale_x_date function

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment