Setting x-axis limits for datetime in ggplot

Use expand parameter in your scale_x_datetime and set it to 0.

scale_x_datetime(labels=date_format("%H:%m"), breaks = date_breaks("2 hours"), expand=c(0,0))

First things first, here is some reproducible data:

set.seed(1)
ParkingSub4 <- data.frame(DateTime = seq(as.POSIXlt('2017-02-22 23:00'), 
                                         as.POSIXlt('2017-02-24 01:00'), 
                                         len = 42), 
                          OccupancyRateShort = runif(42, 0, 1))
ParkingSub4$Weekday <- weekdays(ParkingSub4$DateTime)

Next, here is how to reproduce the problem with this data:

library(ggplot2)
library(scales)
ggplot(data = ParkingSub4[ParkingSub4$Weekday == "Thursday",], 
       aes(x = DateTime, y = OccupancyRateShort)) + 
       geom_line(size = 1.25) + 
       facet_wrap(~Weekday) +
       scale_x_datetime(labels = date_format("%H:%m"), 
                        breaks = date_breaks("2 hours")) +
       theme_linedraw()

Finally, here is a solution using the limits option to scale_x_datetime:

lims <- as.POSIXct(strptime(c("2017-02-23 00:00", "2017-02-24 00:00"), 
                   format = "%Y-%m-%d %H:%M"))
ggplot(data = ParkingSub4[ParkingSub4$Weekday == "Thursday",], 
       aes(x = DateTime, y = OccupancyRateShort)) + 
       geom_line(size = 1.25) + 
       facet_wrap(~Weekday) +
       scale_x_datetime(labels = date_format("%H:%m"), 
                        breaks = date_breaks("2 hours"), 
                        limits = lims) +
       theme_linedraw()

UPDATE: The following will remove the whitespace on the left and right of the graph and the breaks will be on the hour instead of at 2 minutes past:

lims <- as.POSIXct(strptime(c("2017-02-23 00:00", "2017-02-23 23:59"), 
                   format = "%Y-%m-%d %H:%M"))
ggplot(data = ParkingSub4, 
       aes(x = DateTime, y = OccupancyRateShort)) + 
       geom_line(size = 1.25) +            
       scale_x_datetime(labels = date_format("%H:%M"), 
                        breaks = date_breaks("2 hours"), 
                        limits = lims, 
                        expand = c(0, 0)) +
       theme_linedraw()

Tags:

R

Ggplot2