5

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
4
  • You can save yourself a lot of headaches by using the 'lubridate' package, instead of the 'as.Date' function. Commented Aug 16, 2013 at 12:05
  • One thing, related to your problem or not: I think you miss a % in as.Date(value, "%d/%m/Y"). Try as.Date(value, "%d/%m/%Y"). Commented Aug 16, 2013 at 12:27
  • Thanks, it produces the same error. I updated the question Commented Aug 16, 2013 at 12:32
  • Maybe I'm being a bit thick here, but what are you trying to plot, exactly? You want time on the x-axis, but what are you plotting on the y-axis? Commented Aug 16, 2013 at 12:42

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.