scale_datetime shifts x axis [duplicate]
Asked Answered
B

1

3

I am trying to plot a time series that has an x axis of class "POSIXct" using ggplot2, which is working up to a point.

When I try to manipulate the x axis breaks and labels using scale_x_datetime it generates a one month shift in the x axis.

Can anyone explain this, and provide a solution?

Example simplified code:

start <- as.POSIXct("2014/07/01 00:00:00")
end <- as.POSIXct("2014/10/01 23:30:00")
interval <- as.difftime("00:30:00")
df <- data.frame(t=seq(start, end, by="1 day"))
df$v <- sample(1:100, replace=TRUE, nrow(df))

p <- ggplot(data=df, aes(x=t)) +
  geom_line(aes(y=v))

p2 <- p + scale_x_datetime(breaks=date_breaks("1 month"), labels=date_format("%b-%y"))
Bettinabettine answered 29/7, 2016 at 11:9 Comment(0)
C
3

It's a time zone issue. date_format sets the time zone to "UTC" by default and internally calls format.POSIXct which calls as.POSIXlt internally. There this happens:

as.POSIXlt(start, "UTC")
#[1] "2014-06-30 22:00:00 UTC"

Voilà, a different month.

You can avoid this by not changing the time zone:

p + scale_x_datetime(breaks=date_breaks("1 month"), 
                     labels=date_format("%b-%y", tz = Sys.timezone(location = TRUE)))

If you explicitly defined a time zone (you should) when creating the POSIXct variable, you should pass this time zone here.

Conspecific answered 29/7, 2016 at 12:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.