What is the appropriate timezone argument syntax f

2019-02-25 11:52发布

I can't seem to find the information on the ggplot2 0.9.0 documentation, 0.9.0 transition guide, or search.

I guess in earlier versions you'd add the tz argument to scale_x_datetime. I've tried placing the tz argument in different places within scale_x_datetime but keep getting errors. See below.

My datetime data is in POSIXct format with GMT timezone. When I plot it, the axis ticks and breaks are showing my local timezone (EST). I'd like midnight on the axis to be midnight in GMT timezone. What is the right way to do this in ggplot2 0.9.0?

attributes(data$date)
# $class
# [1] "POSIXct" "POSIXt" 

# $tzone
# [1] "GMT"

ggplot(data, aes(x = date)) +
  geom_line(aes(y = count)) +
  scale_x_datetime(breaks = date_breaks("1 day"),
                   labels = date_format("%d", tz = "UTC"))
# Error in date_format("%d", tz = "UTC") : unused argument(s) (tz = "UTC")

ggplot(data, aes(x = date)) +
  geom_line(aes(y = count)) +
  scale_x_datetime(breaks = date_breaks("1 day", tz = "UTC"),
                   labels = date_format("%d"))
# Error in date_breaks("1 day", tz = "UTC") : 
#   unused argument(s) (tz = "UTC")

ggplot(data, aes(x = date)) +
  geom_line(aes(y = count)) +
  scale_x_datetime(breaks = date_breaks("1 day"),
                   labels = date_format("%d"),
                   tz = "UTC")
# Error in continuous_scale(aesthetics, "datetime", identity, breaks = breaks,  : 
#   unused argument(s) (tz = "UTC")

2条回答
Bombasti
2楼-- · 2019-02-25 12:11

Since scales 2.2 (~jul 2012) it is possible to pass tz argument to time_trans.

For instance, that formats timestamps in UTC and requires no additional coding:

+scale_x_continuous(trans = time_trans(tz = "UTC"))
查看更多
神经病院院长
3楼-- · 2019-02-25 12:23

@joran is on the right track, but additional arguments can not be passed through the formatting function, so they need to be passed to the generator function:

date_format_tz <- function(format = "%Y-%m-%d", tz = "UTC") {
  function(x) format(x, format, tz=tz)
}

which could then be called as:

scale_x_datetime(breaks = date_breaks("1 day"),
                 labels = date_format_tz("%d", tz="UTC"))
查看更多
登录 后发表回答