在Vega-Lite中实现多列自定义Tooltip并修复交互异常
Vega-Lite 测验分数可视化问题解决方案
问题1:悬停单个数据圆圈时整列放大的修复
问题根源是默认的选择交互绑定了测验列字段(如quiz),导致同一测验下的所有点被批量选中。只需调整选择器的目标为单个数据点,配合尺寸条件判断即可解决:
{ "mark": {"type": "circle"}, "encoding": { "x": {"field": "quiz", "type": "nominal"}, "y": {"field": "category", "type": "nominal"}, "size": { "value": 100, "condition": { "test": {"param": "hover", "empty": false}, "value": 300 } } }, "params": [ { "name": "hover", "select": {"type": "point", "on": "mouseover", "clear": "mouseout"} } ] }
核心是select: {"type": "point"}会仅选中当前悬停的单个数据点,而非整组,配合size的条件判断,只有目标点会放大。
问题2:Tooltip同时显示归一化分数与实际分数
有两种实现方式,按需选择:
方式1:分字段展示明细
直接在encoding中定义tooltip数组,指定每个字段的显示格式:
"encoding": { // 其他x/y/size编码... "tooltip": [ {"field": "category", "title": "类型"}, {"field": "normalized_score", "title": "归一化分数", "format": ".0%"}, {"field": "actual_score", "title": "实际分数"} ] }
方式2:组合成单条文本(如"Avg: 36%, 62")
通过表达式直接拼接内容,绑定到tooltip:
"mark": { "type": "circle", "tooltip": { "text": {"expr": "'Avg: ' + format(datum.normalized_score, '.0%') + ', ' + datum.actual_score"} } }
如果需要动态匹配不同分类(比如Avg/Max/Min),可以把category字段也加入表达式:
"text": {"expr": "datum.category + ': ' + format(datum.normalized_score, '.0%') + ', ' + datum.actual_score"}
内容的提问来源于stack exchange,提问作者MsA
相关产品推荐
相关产品推荐

