Skip to content

Instantly share code, notes, and snippets.

@mollietaylor
Created June 23, 2013 22:58
Show Gist options
  • Save mollietaylor/5846843 to your computer and use it in GitHub Desktop.
Save mollietaylor/5846843 to your computer and use it in GitHub Desktop.
Plot Weekly or Monthly Totals in R
library(ggplot2)
library(scales)
# 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))
log
str(log)
# convert date variable from factor to date format:
log$Date <- as.Date(log$Date,
"%Y/%m/%d") # tabulate all the options here
str(log)
# 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
log
# 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"
scale_x_date(
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"
scale_x_date(
labels = date_format("%Y-%m-%d"),
breaks = "1 week") # custom x-axis labels
@mielniczuk
Copy link

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

@EthanDeng
Copy link

Excellent cut function example!

@sfgreen
Copy link

sfgreen commented Sep 22, 2015

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

@zfleeman
Copy link

Great way to show off cut(), but the 'scales' library isn't needed to scale the date. The ggplot scale_x_date() can be run with the date_labels argument.

ggplot(data = log, aes(Month, Quantity)) + stat_summary(fun.y = sum, geom = "bar") + scale_x_date(date_labels="%Y-%m", date_breaks = "1 month")

@imdhanashree
Copy link

following code is giving error message as" Error in strsplit(unitspec, " ") : non-character argument" please tell me the solution

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"
scale_x_date(
labels = date_format('%Y-%m'),
breaks = "1 month") # custom x-axis labels

@EasterBeagle
Copy link

@Dhanashree2491 - a quick google search turned up:
https://stackoverflow.com/questions/32653730/ggplot2-scale-x-date

In a nutshell, you must change "breaks" to "date_breaks" in the last line of code you pasted

@Jukang
Copy link

Jukang commented Aug 9, 2020

Thank you for the nice examples!! Is there any way to remove grid bw background and modify the dates on the x-axis to mm/dd/yyyy format?

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