Vega-Lite中按条件隐藏Y轴标签及调整条形图文本位置
分组条形图:数值≥100时隐藏Y轴标签并调整文本位置
针对你的需求,只需对Vega-Lite配置做两处关键修改即可实现效果:
修改步骤
隐藏Y轴上≥100的刻度标签
在Y轴配置中添加labelExpr条件判断,仅显示数值小于100的标签:"y": { "field": "value", "type": "quantitative", "domainMax": 100, "labelExpr": "datum.value < 100 ? datum.label : ''" }将≥100的文本标签移至条形内部
给文本标记添加条件编码,根据数值大小调整标签的Y位置和颜色:{ "mark": { "type": "text", "align": "center" }, "encoding": { "text": {"field": "value", "type": "quantitative"}, "y": { "condition": { "test": "datum.value >= 100", "value": 95 // 固定在条形内部靠近顶部的位置 }, "field": "value", "type": "quantitative", "offset": 5 // 小于100时在条形上方偏移5像素 }, "color": { "condition": { "test": "datum.value >= 100", "value": "white" }, "value": "black" } } }
修改后的完整配置
{ "$schema": "https://vega.github.io/schema/vega-lite/v5.json", "data": { "values": [ {"category": "A", "group": "Group 1", "value": 40}, {"category": "A", "group": "Group 2", "value": 100}, {"category": "B", "group": "Group 1", "value": 70}, {"category": "B", "group": "Group 2", "value": 90}, {"category": "C", "group": "Group 1", "value": 100}, {"category": "C", "group": "Group 2", "value": 50} ] }, "layer": [ { "mark": "bar", "encoding": { "x": {"field": "category", "type": "nominal"}, "y": { "field": "value", "type": "quantitative", "domainMax": 100 }, "xOffset": {"field": "group", "type": "nominal"}, "color": {"field": "group", "type": "nominal"} } }, { "mark": { "type": "text", "align": "center" }, "encoding": { "text": {"field": "value", "type": "quantitative"}, "x": {"field": "category", "type": "nominal"}, "xOffset": {"field": "group", "type": "nominal"}, "y": { "condition": { "test": "datum.value >= 100", "value": 95 }, "field": "value", "type": "quantitative", "offset": 5 }, "color": { "condition": { "test": "datum.value >= 100", "value": "white" }, "value": "black" } } } ], "encoding": { "y": { "field": "value", "type": "quantitative", "domainMax": 100, "labelExpr": "datum.value < 100 ? datum.label : ''" } } }
修改后实现的效果:Y轴不再显示100的刻度标签,数值为100的条形文本移至内部并改为白色,小于100的文本仍在条形上方,且不会超出图表区域。
内容的提问来源于stack exchange,提问作者Mohit
相关产品推荐
相关产品推荐

