【问题标题】:Eliminate timestamp timezone offset in lattice xyplot消除 lattice xyplot 中的时间戳时区偏移
【发布时间】:2016-06-17 06:31:41
【问题描述】:

当使用lattice 绘制每小时时间戳的值时,我发现图表的 x 轴标签中存在从 UTC 到本地时间的恼人时区偏移。虽然此示例使用lubridate,但直接使用POSIXct 时会出现问题。例如:

library(lattice)
library(lubridate)
foo <- data.frame(t = seq(ymd_hms("2015-01-01 00:00:00"),
                          ymd_hms("2015-01-02 00:00:00"), 
                          by = "hour"),
                  y = 1:25)
head(foo)
xyplot(y~t, foo) # time axis is behind by 5 hours (EST = UTC-5)

一种解决方案是明确指定时区:

tz(foo$t) <- ""  # or tz(foo$t) <- "EST"
head(foo)
xyplot(y~t, foo) # time axis now agrees

是否有其他方法可以让lattice 直接在 UTC 中绘制而不修改数据的时区?也许使用scales = list(x = list(format = ...)) 参数?我可以想象更改数据的时区会很糟糕的情况,特别是在处理夏令时事件时。

【问题讨论】:

  • 您是否碰巧找到了解决方案?

标签: r timestamp lattice


【解决方案1】:

蛮力方法是使用数据中的时区临时覆盖系统的时区,并在创建绘图后将其重置为之前的值:

tzn = Sys.getenv("TZ")
Sys.setenv(TZ = tz(foo$t))

xyplot(
  y ~ t
  , data = foo
)

Sys.setenv(TZ = tzn)

【讨论】:

    【解决方案2】:

    这是一个错误;将每个面板的限制组合成一个整体限制的过程(即使只有一个面板)会丢失属性,包括 tz 属性。

    p <- xyplot(y ~ t, foo)
    str(attributes(foo$t))
    # List of 2
    #  $ class: chr [1:2] "POSIXct" "POSIXt"
    #  $ tzone: chr "UTC"
    str(attributes(p$x.limits))
    # List of 1
    #  $ class: chr [1:2] "POSIXct" "POSIXt"
    

    通过设置修复

    attributes(p$x.limits)$tzone <- "UTC"
    

    其他解决方法是

    xyplot(y ~ t, foo, xlim = extendrange(foo$t))
    xyplot(y ~ t, foo, scales = "free")
    

    【讨论】:

      猜你喜欢
      • 2019-09-06
      • 1970-01-01
      • 2018-09-11
      • 1970-01-01
      • 2018-03-04
      • 2012-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多