Search code examples
rtimeplottime-serieschron

Time Series plot with "times" in y-axis


Suppose I have some completion times for an event.

completion_data <- data.frame(
    date=c("2009-05-04", "2010-04-07", "2011-04-02", "2011-05-06",
           "2012-06-03", "2012-07-09", "2013-09-03", "2014-02-01"),
    time_taken=c("1:53:01", "1:50:01", "1:30:01", "1:29:01", 
                 "1:28:03", "1:20:01", "1:15:11", "1:12:24"))

library(zoo)
library(chron)
completion_data$date <- as.Date(completion_data$date)
completion_data$time_taken <- chron(times.=completion_data$time_taken)

I want to create a time series plot with the date on the x-axis and the time taken on the y-axis.

completion_ts <- zoo(completion_data$time_taken, completion_data$date)
plot(completion_ts, ylab="Time (H:M:S)", xlab="Date", type='o')

enter image description here

However, the y-axis doesn't have H:M:S format as I wanted. For instance, the first dot corresponds to a time of 1:53:01 (i.e. 1 hour, 53 minutes, 1 second) and I was hoping to have the y-axis use this format.

  • I would like to do this using base graphics, i.e. not ggplot2 (if possible)
  • One thought I had was to use the axis statement after the plot, but not sure if it possible to plot the times object (created by chron) directly

Solution

  • Put the labels on the Y axis yourself:

    plot(completion_ts, ylab = "Time (H:M:S)", xlab = "Date", type = 'o', yaxt = "n")
    tt <- seq(times("00:00:00"), times("23:59:59"), times("00:10:00"))
    axis(2, tt, sub(":00$", "", times(tt)))
    

    screenshot