date - 在 Vega-Lite 中为日期添加日期
问题描述
我正在尝试在我的日期中添加一天,看起来像 2020 年 11 月 20 日的“2020-11-20”。但是我在这样做时遇到了困难 - 我需要使用偏移功能吗?我这样做的原因是 Vega-Lite 通过其 GMT 转换自动将我的日期偏移回 1 天,我无法让它停止。请帮忙!
这是一个例子。如果您查看时间线图,它在 2020 年 11 月 19 日结束,但我的数据中的最终日期是 2020 年 11 月 20 日,我需要做到这一点,所以 2020 年 11 月 20 日是我时间线图上的最后日期.
解决方案
这个问题来自 javascript 如何解析日期的一个不幸的“功能”。这是您看到的问题的一个最小示例(在编辑器中打开):
{
"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 和 scales 来解决这个问题,但我倾向于发现这种方法有点笨拙。相反,我尝试始终通过完整的 ISO 8601 时间戳在 Vega-Lite 中指定日期。
在您的情况下,最好的方法可能是使用计算转换来规范您的日期,然后从那里开始。修改上面的简化示例,它可能看起来像这样(在编辑器中打开):
{
"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"
}
]
}
}
推荐阅读
- c# - 如果文本文件已经打开,如何避免异常
- c++ - C++ - 使用向量或链表?
- vercel - Vercel 在 api 中获取 DELETE 请求超时
- three.js - ThreeJS 相关。是什么导致 GPU 过载?空闲时间很多但是帧率很低
- azure - Azure Functions 上的 VCRedist 2015+
- javascript - Wordpress 插件中“XXX.min.js”文件的意义
- php - 从 JSON 数据中获取特定值
- visual-studio-code - 保存时运行命令,仅当调试处于活动状态时
- c# - 如何禁用剃刀页面中的面包屑?
- python - TypeError:只能在 Python 中使用“-filter:retweets”将元组(不是“str”)连接到元组