【问题标题】:R: as.POSIXct timezone and scale_x_datetime issues in my datasetR:我的数据集中的 as.POSIXct 时区和 scale_x_datetime 问题
【发布时间】:2016-03-25 19:59:55
【问题描述】:

我花了一些时间试图弄清楚为什么在应用 scale_x_datetime 时小时刻度会发生变化。我试图在创建日期/时间列时给出时区。我使用了 ggplot 和 scale_x_datetime() 包中的 scales。小时刻度错误,哪个数据点与其日期/时间列中的时间不匹配。

这是处理我的数据集的一些程序。

  DF$DateTime<-as.POSIXct(DF$timestamp,format="%m/%d/%y %H:%M", tz="America/Toronto")
  DF$Date<-as.Date(DF$DateTime)

  lims <- as.POSIXct(strptime(c("2015-07-21 00:00","2015-07-23 00:00"), format = "%Y-%m-%d %H:%M"), tz="America/Toronto")    

  ggplot(DF) + geom_line(aes(x=DateTime, y=-Diff,group=Date)) + scale_x_datetime(limits =lims, breaks=date_breaks("2 hour"), labels=date_format("%m/%d %H:%M"))

我错过了什么吗?请帮我弄清楚。 非常感谢!

【问题讨论】:

标签: r ggplot2 posixct


【解决方案1】:

函数date_format() 采用默认设置为"UTC"tz 参数。因此,您的标签将转换为 UTC。要使用“美国/多伦多”时区,您可以执行以下操作:

scale_x_datetime(limits = lims, breaks = date_breaks("2 hour"),
    labels = date_format("%m/%d %H:%M", tz = "America/Toronto"))

此参数是在 0.2.5 版本中引入的。使用 date_format() 在 UTC 以外的其他时区创建绘图的代码必须在更新后更改。

【讨论】:

  • 我需要在data_format中指定tz。您的帖子中有一个类型。应该是这样的:labels = date_format("%m/%d %H:%M", tz = "America/Toronto")
  • @Kuo-HsienChang 你是对的,我纠正了错误。很抱歉!
【解决方案2】:

更新 ggplot 3+。 scale_x_datetime 允许您直接设置 x 轴时区(使用与旧答案中给出的语法略有不同的语法)。现在正确的代码是:

scale_x_datetime(limits = lims, breaks = date_breaks("2 hour"),
                 date_labels = "%m/%d %H:%M",
                 timezone = "America/Toronto")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-16
    • 2018-05-18
    • 1970-01-01
    • 1970-01-01
    • 2015-08-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多