在 Vega-Lite 中将日期添加到日期

Add day to a date in Vega-Lite

我想在我的日期中添加一天,看起来像“2020-11-20”,表示 2020 年 11 月 20 日。但是我在这样做时遇到了困难 - 我需要使用偏移功能吗?我这样做的原因是 Vega-Lite 通过其 GMT 转换自动将我的日期向后偏移 1 天,我无法让它停止。请帮忙!

这是一个example。如果您查看时间线图,它在 2020 年 11 月 19 日结束,但我的数据中的最终日期是 2020 年 11 月 20 日,我需要将它设为 2020 年 11 月 20 日是我时间线图上的最后一个日期.

这个问题来自 javascript 如何解析日期的一个不幸的“特性”。这是您遇到的问题的一个最小示例 (open in editor):

{
  "data": {
    "values": [
      {"date": "2020-11-17", "value": 5},
      {"date": "2020-11-18", "value": 6},
      {"date": "2020-11-19", "value": 7},
      {"date": "2020-11-20", "value": 8}
    ]
  },
  "mark": "bar",
  "encoding": {
    "x": {"field": "value", "type": "quantitative"},
    "y": {
      "field": "date",
      "timeUnit": "yearmonthdate",
      "type": "ordinal"
    },
    "tooltip": [
      {
        "field": "date",
        "timeUnit": "yearmonthdate",
        "type": "temporal"
      }
    ]
  }
}

与输入相比,图表中的每一天都相差一天。那么为什么会这样呢?

好吧,事实证明 Vega-Lite 的渲染器利用了 Javascript 的内置日期解析,并且 Javascript 的日期解析根据输入的方式对输入进行不同的处理'重新格式化。特别是,Javascript 将以 UTC 时间解析非标准时间戳,但将以本地时间解析完整的 ISO-8601 时间戳,您可以在浏览器的 javascript 控制台中确认这一事实(我在计算机设置为 PST):

> new Date('2020-11-20')
Thu Nov 19 2020 16:00:00 GMT-0800 (Pacific Standard Time)

> new Date('2020-11-20T00:00:00')
Fri Nov 20 2020 00:00:00 GMT-0800 (Pacific Standard Time)

Vega-Lite 文档建议使用 UTC timeUnits 和尺度来解决这个问题,但我倾向于发现这种方法有点笨拙。相反,我尝试始终通过完整的 ISO 8601 时间戳在 Vega-Lite 中指定日期。

对于您的情况,最好的方法可能是使用计算转换来规范您的日期,然后从那里开始。修改上面的简化示例,它可能看起来像这样 (open in editor):

{
  "data": {
    "values": [
      {"date": "2020-11-17", "value": 5},
      {"date": "2020-11-18", "value": 6},
      {"date": "2020-11-19", "value": 7},
      {"date": "2020-11-20", "value": 8}
    ]
  },
  "transform": [
    {"calculate": "toDate(datum.date + 'T00:00:00')", "as": "date"}
  ],
  "mark": "bar",
  "encoding": {
    "x": {"field": "value", "type": "quantitative"},
    "y": {
      "field": "date",
      "timeUnit": "yearmonthdate",
      "type": "ordinal"
    },
    "tooltip": [
      {
        "field": "date",
        "timeUnit": "yearmonthdate",
        "type": "temporal"
      }
    ]
  }
}