17

I want to set bounds for the x-axis for a plot of time-series data which features only time (no dates). My limits are:

lims <- strptime(c("03:00","16:00"), format = "%H:%M")

And my ggplot prints fine, but when I add this to scale_x_datetime

scale_x_datetime(limits = lims)

I get Error: Invalid input: time_trans works with objects of class POSIXct only

Fully reproducible example courtesy of How to create a time scatterplot with R?

dates <- as.POSIXct(as.Date("2011/01/01") + sample(0:365, 100, replace=TRUE))
times <- as.POSIXct(runif(100, 0, 24*60*60), origin="2011/01/01")
df <- data.frame(
  dates = dates,
  times = times
)

lims <- strptime(c("04:00","16:00"), format = "%H:%M")

library(scales)
library(ggplot2)

ggplot(df, aes(x=dates, y=times)) + 
  geom_point() + 
  scale_y_datetime(limits = lims, breaks=date_breaks("4 hour"), labels=date_format("%H:%M")) + 
  theme(axis.text.x=element_text(angle=90))
Community
  • 1
  • 1
raphael
  • 2,762
  • 5
  • 26
  • 55

1 Answers1

23

the error message says that you should use as.POSIXct on lims. You also need to add the date (year, month and day) in lims, because by default it will be `2015, which is off limits.

lims <- as.POSIXct(strptime(c("2011-01-01 03:00","2011-01-01 16:00"), format = "%Y-%m-%d %H:%M"))    
ggplot(df, aes(x=dates, y=times)) + 
    geom_point() + 
    scale_y_datetime(limits =lims, breaks=date_breaks("4 hour"), labels=date_format("%H:%M"))+ 
    theme(axis.text.x=element_text(angle=90))
Mamoun Benghezal
  • 5,264
  • 7
  • 28
  • 33