在 Vega-lite 的工具提示中将时间戳格式化为日期

问题描述

我有 this chart 可以从 CSV 中获取数据,按其中一列旋转并显示多个带线的时间序列。还制作一个工具提示自动从数据透视列中获取名称

stock chart with tooltip and several stock lines

唯一的问题是日期/时间显示为时间戳。有没有办法将它格式化为更好看,比如实际的日期 + 时间,就像它在 X 轴上的显示方式一样?

我知道我可以指定工具提示的所有值,做类似的事情

        "tooltip": [
    {
        "field": "date","type": "temporal","title": "date","timeUnit": "utcyearmonthdatehoursminutes"
    },{...}
]

但我希望能够继续使用 "mark": {"type": "rule","tooltip": {"content": "data"}}, 来动态获取工具提示字段,如果我添加上面的代码,则工具提示中只会显示日期。

完整代码如下:

{
  "$schema": "https://vega.github.io/schema/vega-lite/v5.json","data": {"url": "data/stocks.csv"},"width": 400,"height": 300,"encoding": {"x": {"field": "date","type": "temporal"}},"layer": [
    {
      "encoding": {
        "color": {"field": "symbol","type": "nominal"},"y": {"field": "price","type": "quantitative"}
      },"layer": [
        {"mark": "line"},{"transform": [{"filter": {"param": "hover","empty": false}}],"mark": "point"}
      ]
    },{
      "transform": [{"pivot": "symbol","value": "price","groupby": ["date"]}],"mark": {"type": "rule","encoding": {
        "opacity": {
          "condition": {"value": 0.3,"param": "hover","empty": false},"value": 0
        }
      },"params": [{
        "name": "hover","select": {
          "type": "point","fields": ["date"],"nearest": true,"on": "mouSEOver","clear": "mouSEOut"
        }
      }]
    }
  ]
}

解决方法

您可以在计算转换中格式化日期字段并分配新字段,然后该字段将显示在您的工具提示中。 只需添加以下转换代码或检查 editor。有关更多格式或日期表达式,请参阅 https://vega.github.io/vega/docs/expressions

"transform": [
        {"pivot": "symbol","value": "price","groupby": ["date"]},{"calculate": "datetime(datum.date)","as": "convertedDate"},{
          "calculate": "utcFormat(datum.date,'%B %d,%Y')","as": "converted as string"
        }
      ],

如果您想更新现有的日期字段,只需在 as 配置中提供日期字段,如下所示:

 {"calculate": "datetime(datum.date)","as": "date"},