Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to plot time interval data using ggplot2

Tags:

r

ggplot2

I have a data.frame like this:

library(ggplot2)
library(reshape2)    
tasks <- c("Review literature", "Mung data")
    dfr <- data.frame(
      name        = factor(tasks, levels = tasks),
      start.date  = c("24/08/2010 01:00:01", "24/08/2010 01:00:10", "01/11/2010 01:30:00", "01/11/2010 02:00:00"),
      end.date    = c("24/08/2010 02:00:00", "24/08/2010 03:00:00", "01/11/2010 02:00:00", "01/11/2010 04:00:00")
    )
    mdfr <- melt(dfr, measure.vars = c("start.date", "end.date"))

I would like to plot this data using ggplot2 so that different dates are on different facets and only time portion is show on x-axis? I tried something like:

ggplot(mdfr, aes(as.Date(value, "%H/%M/%S"), name)) + 
   geom_line(size = 6) +
   xlab("") + ylab("") +
   theme_bw() + facet_wrap(~as.Date(value, "%d/%m/%Y"))

Error in layout_base(data, vars, drop = drop) : 
  At least one layer must contain all variables used for facetting
like image 705
Matkrupp Avatar asked Oct 03 '22 05:10

Matkrupp


1 Answers

Added to your melted data frame two new columns value2 and date. value2 is POSIXct class of your times and date column contains just date part of your original value and converted to factor to use for faceting.

mdfr$value2<-as.POSIXct(strptime(mdfr$value, "%d/%m/%Y %H:%M:%S"))
mdfr$date<-as.factor(as.Date(strptime(mdfr$value, "%d/%m/%Y %H:%M:%S")))

Now you can use new value2 as x and date for facetting. I used facet_grid() with scales="free_x" and space="free_x" to get evenly spaced time intervals in both facets.

ggplot(mdfr, aes(value2, name)) + 
  geom_line(size = 6) +
  xlab("") + ylab("") +
  theme_bw() + facet_grid(~date,scales="free_x",space="free_x")

enter image description here

like image 103
Didzis Elferts Avatar answered Oct 07 '22 18:10

Didzis Elferts