Skip to content

Instantly share code, notes, and snippets.

@neilfws
Created April 13, 2010 13:59
Show Gist options
  • Save neilfws/364641 to your computer and use it in GitHub Desktop.
Save neilfws/364641 to your computer and use it in GitHub Desktop.
Gantt chart (per day) using ggplot2
library(ggplot2)
# read data file tasks.csv - it looks like this:
# task,date,start,end
# task1,2010-03-05,09:00:00,13:00:00
# task2,2010-03-06,10:00:00,15:00:00
# task3,2010-03-06,11:00:00,18:00:00
# task4,2010-03-07,08:00:00,11:00:00
# task5,2010-03-08,14:00:00,17:00:00
# task6,2010-03-09,12:00:00,16:00:00
# task7,2010-03-10,14:00:00,19:00:00
# task8,2010-03-11,09:30:00,13:30:00
tasks <- read.csv("tasks.csv", header = T)
# day of week
tasks$day <- weekdays(strptime(tasks$date, "%Y-%m-%d"))
week <- c("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday")
tasks$day <- factor(tasks$day, levels = week)
# convert time to decimal hours
tasks$start.ct <- as.POSIXct(paste(tasks$date, tasks$start, sep = " "))
tasks$end.ct <- as.POSIXct(paste(tasks$date, tasks$end, sep = " "))
tasks$start.hour <- as.POSIXlt(tasks$start.ct)$hour + as.POSIXlt(tasks$start.ct)$min/60 + as.POSIXlt(tasks$start.ct)$sec/3600
tasks$end.hour <- as.POSIXlt(tasks$end.ct)$hour + as.POSIXlt(tasks$end.ct)$min/60 + as.POSIXlt(tasks$end.ct)$sec/3600
# offset tasks if > 1 per day
tasks$ymin <- c(rep(0, nrow(tasks)))
t <- table(tasks$day)
for(day in rownames(t)) {
if(t[[day]] > 1) {
ss <- tasks[tasks$day == day,]
y <- 1.2
for(i in as.numeric(rownames(ss))) {
tasks[i,]$ymin <- y
y <- y + y
}
}
}
# plot
png(filename = "tasks.png", width = 640, height = 480)
ggplot(tasks, aes(xmin = start.hour, xmax = end.hour, ymin = ymin, ymax = ymin + 1, fill = factor(task))) + geom_rect() + facet_grid(day~.) + opts(axis.text.y = theme_blank(), axis.ticks = theme_blank()) + xlim(0,23) + xlab("time of day")
dev.off()
@Gopal-OSI
Copy link

I'm using R 3.2.3.
In the ggplot call, I got an error saying that opts and theme_blank are not recognized.
It worked with following corrections:
ggplot(tasks, aes(xmin = start.hour, xmax = end.hour, ymin = ymin, ymax = ymin + 1, fill = factor(task))) + geom_rect() + facet_grid(day~.) + theme(axis.text.y = element_blank(), axis.ticks = element_blank()) + xlim(0,23) + xlab("time of day")

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