Search code examples
rggplot2lubridate

Set interval between breaks on time axis


First let's create some example data. The times are stored using lubridate's hm as this seems the most suitable.

library(tibble)
library(lubridate)
#> 
#> Attaching package: 'lubridate'
#> The following object is masked from 'package:base':
#> 
#>     date

(
  data <- tibble(
    Time = hm('09:00', '10:30'),
    Value = 1
  )
)
#> # A tibble: 2 x 2
#>   Time         Value
#>   <S4: Period> <dbl>
#> 1 9H 0M 0S         1
#> 2 10H 30M 0S       1

Here's how I'd like the plot to look. For now I've specified the breaks manually at half-hour intervals.

library(ggplot2)
library(scales)

ggplot(data, aes(Time, Value)) +
  geom_point() +
  scale_x_time(breaks = hm('09:00', '09:30', '10:00', '10:30'))

I'd like to create these breaks automatically at half-hour intervals. Trying to use scales::date_breaks gives an error.

ggplot(data, aes(Time, Value)) +
  geom_point() +
  scale_x_time(breaks = date_breaks('30 mins'))
#> Error in UseMethod("fullseq"): no applicable method for 'fullseq' applied to an object of class "c('hms', 'difftime')"

Trying to create the breaks using seq also gives an error.

seq(hm('09:00'), hm('10:30'), hm('00:30'))
#> Note: method with signature 'Period#ANY' chosen for function '-',
#>  target signature 'Period#Period'.
#>  "ANY#Period" would also be valid
#> estimate only: convert to intervals for accuracy
#> Error in if (sum(values - trunc(values))) {: argument is not interpretable as logical

Solution

  • Using new breaks_width() function from the package scales.

    ggplot(data, aes(Time, Value)) +
      geom_point() +
      scale_x_time(breaks = scales::breaks_width("30 min"))