14

I spent some time trying to figure out why the hour ticks were shifted when scale_x_datetime was applied. I've tried to give the timezone when the Date/Time column was created. I used ggplot and scale_x_datetime() from the package scales. The hour ticks were wrong, which datapoint did not match the time in their Date/Time column.

Here is some procedures to deal with my dataset.

  DF$DateTime<-as.POSIXct(DF$timestamp,format="%m/%d/%y %H:%M", tz="America/Toronto")
  DF$Date<-as.Date(DF$DateTime)

  lims <- as.POSIXct(strptime(c("2015-07-21 00:00","2015-07-23 00:00"), format = "%Y-%m-%d %H:%M"), tz="America/Toronto")    

  ggplot(DF) + geom_line(aes(x=DateTime, y=-Diff,group=Date)) + scale_x_datetime(limits =lims, breaks=date_breaks("2 hour"), labels=date_format("%m/%d %H:%M"))

Do I miss anything here?? Please help me to figure it out. Many thanks!

Kuo-Hsien Chang
  • 925
  • 17
  • 40
  • Related https://github.com/tidyverse/ggplot2/issues/4007 & https://community.rstudio.com/t/problem-with-scale-x-datetime-timezone-parameter/66314 – Tung Feb 09 '21 at 05:54

2 Answers2

15

The function date_format() takes a tz argument that is by default set to "UTC". Therefore, your labels are converted to UTC. To use the time zone "America/Toronto", you can do the following:

scale_x_datetime(limits = lims, breaks = date_breaks("2 hour"),
    labels = date_format("%m/%d %H:%M", tz = "America/Toronto"))

This argument was introduced with version 0.2.5. Code that uses date_format() to create plots in other time zones than UTC must be changed after the update.

Stibu
  • 15,166
  • 6
  • 57
  • 71
  • 2
    I need to specify the tz in the data_format. There is a type in your post. It should be like this: labels = date_format("%m/%d %H:%M", tz = "America/Toronto") – Kuo-Hsien Chang Mar 26 '16 at 22:16
  • @Kuo-HsienChang You are right and I corrected the mistake. Sorry about that! – Stibu Mar 27 '16 at 08:13
5

Update for ggplot 3+. scale_x_datetime allows you to set the x-axis time zone directly (using a syntax slightly different than that given in older answers). The correct code now is:

scale_x_datetime(limits = lims, breaks = date_breaks("2 hour"),
                 date_labels = "%m/%d %H:%M",
                 timezone = "America/Toronto")
Richard Sprague
  • 333
  • 2
  • 6