Setting limits using scale_x_datetime and time data

I want to set the boundaries for the x axis for a graph of time series data that only shows time (no dates). My limits:

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 scatter plot using 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)) 
+8
r time-series ggplot2
source share
1 answer

the error message says you should use as.POSIXct on as.POSIXct . You also need to add the date (year, month and day) to lims , because by default it will be `2015, which does not correspond to the 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)) 
+9
source share

All Articles