Search code examples
rdatetimeplotstrptimeas.date

Create a plot with time on the x- and y-axis (in R)


There are two points in time (two measurements), I would like to plot the first time on the x-axis and the second on the y-axis as points, hence I could easily inspect data-points above the 45°-line for which the second measurement is after the first time (true for most, but not all cases) and evaluate the time elapsed from the first moment.

I therefore have two columns with dates, I can transform them to date or date-time objects. I cannot eastimate right now, which format may allow an easier implemention of the plot.

D = data.frame(time1 = c("2007-06-22","2007-05-22","2007-05-23"), time2 = c("2007-06-22","2007-05-24","2007-06-05"))
D$time1 <- strptime(D$time1, format = "%Y-%m-%d")
D$time2 <- strptime(D$time2, format = "%Y-%m-%d")
class(D$time1)
D$time1 <- as.Date(D$time1, format = "%Y-%m-%d")
class(D$time1)

I need something as easy as:

plot(D$time1, D$time2)

But I also need a modifiable version, which does not plot the days, but allows for breaks (weeks, month, years), say month.

enter image description here

Thank you so much for ideas.

Solution: Both versions worked in principle. I've chosen the ggplot because one's more flexible on labels etc. I did the data-cleaning in advance, so after subsetting missing data, I used:

library( ggplot2 )
ggplot( mydata, aes(x=t0, y=t1) ) + geom_point() +
  scale_x_date(date_labels = "%b %y", date_breaks = "3 month") +
  scale_y_date(date_labels = "%b %y", date_breaks = "3 month") 

3 month are a good break for my 2 years of data. Here's my solution:

enter image description here


Solution

  • ggplot understands time/date data. Use the Date class, as you've done in the question:

    D <- data.frame( time1 = as.Date(c("2007-06-22","2007-05-22","2007-05-23")),
                    time2 = as.Date(c("2007-06-22","2007-05-24","2007-06-05")) )
    

    Now you can pass it to ggplot, using scale_x_date and scale_y_date to achieve flexibility in specifying breaks/labels/etc.:

    library( ggplot2 )
    ggplot( D, aes(x=time1, y=time2) ) + geom_point() +
        scale_x_date( date_labels = "%b %d", date_breaks = "1 week") +
        scale_y_date( date_labels = "%b %d", date_breaks = "1 day" )
    

    See ?scale_x_date for more information.

    enter image description here