如何创建带目标线、条件文本及趋势渐变面积图的Vega Lite KPI卡片?
Vega Lite KPI卡片实现方案
核心需求对应实现点
- 渐变面积趋势图:使用
area标记配合线性渐变填充 - 目标线:通过
rule标记绘制横向参考线 - 条件文本:利用
condition根据数值与目标的关系显示不同状态文本
完整代码示例
{ "$schema": "https://vega.github.io/schema/vega-lite/v5.json", "data": { "values": [ {"date": "2024-01", "value": 42}, {"date": "2024-02", "value": 48}, {"date": "2024-03", "value": 55}, {"date": "2024-04", "value": 62}, {"date": "2024-05", "value": 68}, {"date": "2024-06", "value": 75} ] }, "layer": [ // 渐变面积趋势图 { "mark": {"type": "area", "line": {"color": "#2c7fb8"}}, "encoding": { "x": {"field": "date", "type": "ordinal", "axis": null}, "y": {"field": "value", "type": "quantitative", "axis": null}, "fill": { "gradient": "linear", "x1": 0, "y1": 0, "x2": 0, "y2": 1, "stops": [ {"offset": 0, "color": "#2c7fb8", "opacity": 0.8}, {"offset": 1, "color": "#2c7fb8", "opacity": 0.1} ] } } }, // 目标线 { "mark": {"type": "rule", "color": "#ff7f0e", "strokeDash": [5, 3]}, "encoding": {"y": {"datum": 60, "title": "目标值"}} }, // KPI主数值 { "mark": {"type": "text", "y": -10, "fontSize": 36, "fontWeight": "bold"}, "encoding": { "text": {"field": "value", "aggregate": "max"}, "color": { "condition": {"test": "datum.max_value > 60", "value": "#2c7fb8"}, "value": "#d62728" } } }, // 条件状态文本 { "mark": {"type": "text", "y": 25, "fontSize": 16}, "encoding": { "text": { "condition": {"test": "datum.max_value > 60", "value": "已达标"}, "value": "未达标" }, "color": { "condition": {"test": "datum.max_value > 60", "value": "#2c7fb8"}, "value": "#d62728" } } } ], "width": 300, "height": 200, "config": {"view": {"stroke": null}} }
关键部分说明
- 渐变面积图:通过
fill属性定义线性渐变,设置起止点和透明度变化,让趋势图视觉层次更丰富。 - 目标线:使用
rule标记,通过datum直接指定目标值(示例中为60),添加虚线样式增强与趋势线的区分度。 - 条件文本:利用
condition判断最新/最大数值与目标值的关系,动态显示状态文本并搭配对应警示色,直观反馈KPI完成情况。 - 布局优化:隐藏坐标轴,通过调整文本的
y偏移量控制KPI数值和状态文本的位置,确保卡片整体紧凑美观。
内容的提问来源于stack exchange,提问作者APB Reports
相关产品推荐
相关产品推荐

