Constantine
Constantine

Reputation: 488

Bug with ggplot2 scale_x_datetime

I have an annoying bug with scale_x_datetime ...

plt = ggplot() + geom_line(data=d, aes(Time, d[, 2]), color=col) +
        scale_x_datetime(breaks = seq(d[1,1],d[dim(d)[1],1],interval*60))

Produces a correct time stamp on the plot at the specified intervals... However, if I add date_labels = "%m-%d %H:%M" to format the way the time stamp gets printed on the plot, suddenly the hour value is off by 5 hours...

The following code produces the wrong hour value on the plot

plt = ggplot() + geom_line(data=d, aes(Time, d[, 2]), color=col) +
        scale_x_datetime(date_labels = "%m-%d %H:%M",
                         breaks = seq(d[1,1],d[dim(d)[1],1],interval*60))

For the sake of reproducability...

d = data.frame(Time = as.POSIXct(seq(1446871740, 1446893340, 60), origin = "1970-01-01"),
               Value = rnorm(361))
interval = floor(as.numeric(difftime(d[dim(d)[1],1], d[1,1], units="mins")) / 3)
col = "red"

Upvotes: 1

Views: 753

Answers (1)

aosmith
aosmith

Reputation: 36076

This is a timezone issue. In versions of ggplot2 prior to ggplot2_2.2.0 you would need to set the timezone when you set the labels in scale_x_datetime.

scale_x_datetime(labels = scales::date_format("%m-%d %H:%M", tz = "America/Los_Angeles")

This is no longer an issue for ggplot2_2.2.0. From the news:

scale_*_datetime() now supports time zones. It will use the timezone attached to the variable by default, but can be overridden with the timezone argument.

Updating your ggplot2 to the current version will solve the time shifting issue for your second plot. If you want to set a different timezone, there is now a timezone argument to scale_*_datetime.

Upvotes: 1

Related Questions