What is the appropriate timezone argument syntax for scale_datetime() in ggplot 0.9.0

无人久伴 提交于 2019-12-20 02:35:06

问题


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")

回答1:


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"))



回答2:


@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"))


来源:https://stackoverflow.com/questions/10339618/what-is-the-appropriate-timezone-argument-syntax-for-scale-datetime-in-ggplot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!