You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Vega-Lite中根据数值条件填充形状路径坐标颜色?

在Vega-Lite中实现象形分数图

可以实现类似的象形分数图效果。核心思路是通过裁剪矩形限制填充形状的显示范围,使其仅展示数值对应的部分,再叠加一个完整的轮廓形状呈现整体外观。

以下是调整后的代码,当Value为49时,形状会填充到对应位置:

{"$schema": "https://vega.github.io/schema/vega-lite/v5.json",
 "data": { 
   "name": "mydata",
   "values": [{"Pic": "Pic", "Value":49}]
 },
 "vconcat": [{
   "encoding": {
     "x": {"field": "Pic", "type": "nominal"}
   },
   "layer": [
     // 裁剪矩形(不可见,用于限制填充形状范围)
     {
       "mark": {"type": "rect", "name": "clipRect", "opacity": 0},
       "encoding": {
         "y": {"field": "Value", "type": "quantitative", "scale": {"domain": [0,100]}},
         "y2": {"datum": 0},
         "x": {"datum": -10},
         "x2": {"datum": 20}
       }
     },
     // 填充的形状(被裁剪到Value对应的高度)
     {
       "mark": {
         "type": "point",
         "shape": "M 0 0 L 18 0 L 3 -100 L -12 0 L 0 0", // 适配0-100范围的形状路径
         "fill": "#4CAF50",
         "clip": {"expr": "clipRect"} // 引用裁剪矩形
       },
       "encoding": {"y": {"datum": 50}} // 形状垂直居中
     },
     // 完整的形状轮廓
     {
       "mark": {
         "type": "point",
         "shape": "M 0 0 L 18 0 L 3 -100 L -12 0 L 0 0",
         "fill": "none",
         "stroke": "#333",
         "strokeWidth": 2
       },
       "encoding": {"y": {"datum": 50}}
     },
     // 数值标记线
     {
       "mark": {"type": "rule", "x2": 100, "strokeDash": [4,4]},
       "encoding": {"y": {"field": "Value", "type": "quantitative", "scale": {"domain": [0,100]}}}
     },
     // 数值文本
     {
       "mark": {"type": "text", "align": "left", "baseline": "middle", "dx": 90, "size":20},
       "encoding": {
         "y": {"field": "Value", "type": "quantitative", "scale": {"domain": [0,100]}},
         "text": {"field": "Value", "type": "quantitative"}
       }
     }
   ]
 }]
}

关键调整说明:

  • 形状路径适配:重新定义形状路径,使其Y轴范围从0(底部)到-100(顶部),匹配数值域[0,100],确保填充比例准确。
  • 裁剪范围控制:通过不可见的裁剪矩形,动态限制填充形状的显示区域,仅保留数值对应的下部区域。
  • 双层形状叠加:填充形状被裁剪后,叠加无填充的轮廓形状,完整展示图形边界。
  • 坐标对齐优化:将形状Y轴位置设为50,确保图形在数值轴上垂直居中。

你可根据需求调整形状路径、填充色、轮廓样式等参数,适配不同的象形图形场景。

内容的提问来源于stack exchange,提问作者sen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 21:06:02