Vega-Lite图表渲染日期时间戳时如何保留数据中的null值
问题原因
你当前配置为x字段指定了hoursminutes时间单位和time类型格式化规则,null值在时间单位解析阶段会被默认转换为Unix时间戳起点(1970-01-01T00:00:00Z),对应东八区时区就会显示为04:00,因此出现null值被错误识别为固定时间的问题。
解决方法
通过transform预处理字段,将null值和有效时间值分开处理,保留null值的独立分类:
- 新增计算字段,将null值标记为固定文本,有效时间值保留格式化后的时间展示
- 修改x轴编码规则,改用预处理后的字段,移除原有的时间自动转换规则
- 对应调整tooltip的展示逻辑,适配预处理后的字段
修改后的完整配置如下:
{ "$schema": "https://vega.github.io/schema/vega-lite/v5.json", "data": { "values": [ { "x": null, "y": "recoPU8F3Asuc8t3n" }, { "x": "2017-06-02T07:00:00.000Z", "y": "reco056sZzsAd7qVp" }, { "x": null, "y": "reclQZbw7CiAegm1f" }, { "x": "2017-07-14T07:00:00.000Z", "y": "recAzUhUdekIdkSVt" }, { "x": null, "y": "rec0NHCpaRDP9W1pd" }, { "x": null, "y": "recPYz3QNpXgrmBVy" } ] }, "config": { "range": { "category": [ "#46bfdd" ] }, "legend": { "disable": false, "labelColor": "#333", "labelFontSize": 11, "symbolSize": 30, "rowPadding": 4, "symbolType": "circle", "symbolStrokeWidth": 0, "titleColor": "#666666", "titleFontSize": 11, "titlePadding": 10, "titleFontWeight": 50, "orient": "right" }, "axisY": { "tickMinStep": 1, "format": "~s", "formatType": "number" }, "axis": { "domainColor": "#E8E8E8", "gridColor": "#E8E8E8", "tickColor": "#E8E8E8", "grid": true, "gridWidth": 1, "labelColor": "#666666", "labelFontSize": 11, "labelLimit": 180, "titleColor": "#999999", "tickSize": 16, "titleFontSize": 13, "titlePadding": 10, "titleFontWeight": 40, "labelPadding": 4, "titleLimit": 180 }, "autosize": { "type": "fit", "contains": "padding" }, "axisLeft": { "labelFontSize": 11, "labelColor": "#999999", "labelLimit": 180, "titleFontSize": 13, "titleFontWeight": 40, "titleLimit": 180 }, "style": { "label": { "align": "left", "baseline": "middle", "dx": 4 }, "cell": { "stroke": "transparent" } } }, "mark": { "type": "bar", "width": { "band": 0.7 }, "tooltip": true, "cornerRadiusEnd": 3, "cursor": "pointer", "color": "#4787cd" }, "params": [ { "name": "highlight", "select": { "type": "point", "on": "mouseover" } }, { "name": "select", "select": "point" } ], "encoding": { "x": { "field": "formatted_x", "type": "nominal", "axis": { "labelAngle": -90, "title": "预约时间" }, "sort": { "encoding": "x", "order": "ascending" } }, "y": { "field": "y", "type": "quantitative", "aggregate": "count", "axis": { "title": "记录数量" } }, "tooltip": [ { "field": "formatted_x", "title": "预约时间" }, { "field": "y", "type": "quantitative", "aggregate": "count", "title": "记录数量" } ], "fillOpacity": { "condition": [ { "param": "select", "value": 1 } ], "value": 0.3 }, "strokeWidth": { "condition": [ { "param": "select", "empty": false, "value": 2 }, { "param": "highlight", "empty": false, "value": 1 } ], "value": 0 } }, "transform": [ { "calculate": "datum.x === null ? '无预约时间' : timeFormat(toDate(datum.x), '%I:%M')", "as": "formatted_x" } ], "height": 372, "width": 536 }
修改后null值会单独作为「无预约时间」分类展示,不会被错误转换为04:00,有效时间会正常按%I:%M格式展示,统计计数逻辑保持不变。
内容的提问来源于stack exchange,提问作者noodles life
相关产品推荐
相关产品推荐

