Search code examples
rggplot2chron

plot chron times as hours from origin


I have a set of chron times that is the difference between two time points. These values range from slightly negative to slightly greater than 1. Chron displays these values as a fraction of days because some of the values are greater than 1.

When I plot these values in ggplot, I tried using scale_y_chron() to correctly annotate the y axis, however scale_y_chron() appears to only plot time within a 24 hour period. Is there any way that I can annotate the axis as HH:MM from 00:00?

# data:

time_to <- c(0.19305556,0.12083333,0.58402778,0.32986111,0.40486111,
             0.77083333,0.18263889,0.23472222,0.10138889,0.11666667,
             0.47222222,0.14166667,0.15694444,0.24166667,0.16666667,
             0.29166667,0.28194444,0.16875000,0.42777778,0.88750000,
             0.17916667,0.05763889,0.53263889,0.11666667,0.22916667,
             0.75069444,0.98680556,1.29930556,0.78263889,0.73611111,
             0.73958333,1.22708333,0.41319444,0.98402778,1.22500000,
             0.33194444,0.95972222,0.18333333,0.11458333,0.86805556)

# plot:

require(chron)
require(ggplot2)
qplot(y=time_to)

enter image description here

The y-axis should ideally state total hours from 00:00, but it defaults to days if the time difference is greater than 24 hours.


Solution

  • time_to is just a vector of numbers and so there is no reason to think the axes would be labelled by anything other than numbers. If those numbers represent the difference between two chron datetimes and we want HH:MM format even if greater than 24 hours use a custom label. Make use of the fact that in chron a day is 1 so one hour is 1/24:

    library(ggplot2)
    
    hrs <- seq(0, 30, 5)  # 0, 5, 10, ..., 30
    qplot(y = time_to) + 
       scale_y_continuous(breaks = hrs/24, labels = sprintf("%02d:00", hrs))
    

    screenshot