如何在Vega-Lite柱状图中添加文本标签?
解决Vega-Lite柱状图文本标签不显示问题
你的文本标签未显示的核心原因是未指定文本的x/y定位编码,Vega-Lite无法确定文本的渲染位置。同时因为图表高度仅为26,还需要调整文本的位置参数确保其在可见区域内。
以下是修复后的完整代码:
{ "$schema": "https://vega.github.io/schema/vega-lite/v5.json", "background": "#EFF1EF", "width": 500, "height": 26, "autosize": "pad", "data": { "values": [ { "standarts": { "divisions": [ { "a": { "mean": 135, "part1": 10, "part2": 60, "part5": 130, "part7": 198, "part9": 255, "goal": { "value": 150 } } } ] } } ] }, "transform": [ {"calculate": "datum.standarts.divisions", "as": "D"}, {"flatten": ["D"]}, {"calculate": "datum.D.a", "as": "x"} ], "encoding": { "x": {"field": "x", "type": "quantitative", "scale": {"domain": [0, 300]}, "stack": null}, "opacity": {"value": 1} }, "layer": [ { "mark": {"type": "bar", "color": "#b2b7b4", "cornerRadius": 40}, "encoding": {"x": {}} }, { "mark": {"type": "bar", "color": "#0ef9e5", "height": 25}, "encoding": {"x": {"field": "x.mean"}} }, { "mark": {"type": "text", "align": "center", "fontSize": 12, "dy": 0, "color": "#333"}, "encoding": { "text": {"field": "x.mean"}, "x": {"field": "x.mean"}, "y": {"value": 0} } }, { "mark": {"type": "rule"}, "encoding": { "x": { "field": "x.goal.value", "title": ["Target"], "axis": { "titleFont": "Google Sans", "titleFontSize": 16, "titleFontWeight": 700, "titleY": 8 } } } } ], "config": { "axis": {"ticks": false, "labels": false, "domain": false}, "rule": { "strokeWidth": 4, "strokeDash": [0.2, 8], "strokeCap": "round", "align": "center" } } }
关键修改说明:
- 为文本层添加
x编码,绑定x.mean字段,让文本精准定位在蓝色柱子的末端位置 - 添加
y编码并设置为0,让文本垂直居中于图表区域 - 调整
fontSize(设置为12)和dy(设置为0)参数,适配图表的小高度,避免文本被截断或超出可视范围 - 新增
color设置为深灰色,确保文本与背景和蓝色柱子有足够对比度,提升可读性
内容的提问来源于stack exchange,提问作者newDev
相关产品推荐
相关产品推荐

