How to format axis date_time label in `ggplot2`?

42 Views Asked by At

I am trying to plot a time series, and notice that the date_time label for the x-axis is not formatting as expected.

library(ggplot2)
My_df = data.frame(My_datetime = seq(from = as.POSIXct("2019-05-21 8:00:00"), 
                                     to = as.POSIXct("2019-05-22 23:00:00"), 
                                     by = "10 min"),
                   My_data = sin(1:235))

ggplot(data = My_df) +
  geom_line(aes(x = My_datetime, y = My_data)) + 
  scale_x_datetime(breaks = c(as.POSIXct("2019-05-21 9:00:00"), 
                              as.POSIXct("2019-05-21 15:00:00"), 
                              as.POSIXct("2019-05-22 21:00:00")), 
                   labels=scales::date_format("%m-%d %H:%M"))

I'd like to show only three x-axis labels: 05-21 09:00, 05-21 15:00, and 05-22 21:00. However, it now shows as 05-21 15:00, 05-21 21:00, and 05-23 03:00. I wonder how to fix this? Thank you.

enter image description here

1

There are 1 best solutions below

2
Andy Baxter On BEST ANSWER

Time zones are messing with your outputs! For safety, use lubridate::as_datetime:

library(ggplot2)
My_df = data.frame(My_datetime = seq(from = lubridate::as_datetime("2019-05-21 8:00:00"), 
                                     to = lubridate::as_datetime("2019-05-22 23:00:00"), 
                                     by = "10 min"),
                   My_data = sin(1:235))

ggplot(data = My_df) +
  geom_line(aes(x = My_datetime, y = My_data)) + 
  scale_x_datetime(breaks = c(lubridate::as_datetime("2019-05-21 9:00:00"), 
                              lubridate::as_datetime("2019-05-21 15:00:00"), 
                              lubridate::as_datetime("2019-05-22 21:00:00")), 
                   labels=scales::date_format("%m-%d %H:%M"))