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

基于参数选择动态显示或隐藏Vega-Lite的Line/Rule标记

基于参数切换Vega-Lite图表中的标记显示

完全可以通过定义参数并结合条件可见性实现需求。下面是修改后的完整配置,添加了下拉选择器让用户切换显示line或rule标记:

{
  "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
  "data": {"url": "data/stocks.csv"},
  // 定义参数:创建单选下拉框,选项为line和rule
  "params": [
    {
      "name": "selectedMark",
      "value": "line",
      "bind": {
        "input": "select",
        "options": ["line", "rule"],
        "label": "选择要显示的标记:"
      }
    }
  ],
  "layer": [
    {
      "mark": "line",
      // 仅当参数值为line时显示该图层
      "visibility": {"condition": {"param": "selectedMark", "equal": "line"}, "value": true},
      "encoding": {
        "x": {"field": "date", "type": "temporal"},
        "y": {"field": "price", "type": "quantitative"},
        "color": {"field": "symbol", "type": "nominal"}
      }
    },
    {
      "mark": "rule",
      // 仅当参数值为rule时显示该图层
      "visibility": {"condition": {"param": "selectedMark", "equal": "rule"}, "value": true},
      "encoding": {
        "y": {"field": "price", "aggregate": "mean"},
        "size": {"value": 2},
        "color": {"field": "symbol"}
      }
    }
  ]
}

关键说明:

  • 参数定义:通过params字段创建名为selectedMark的参数,绑定到下拉选择器,默认选中line。
  • 图层可见性控制:每个图层添加visibility属性,使用condition判断当前参数值是否匹配图层对应的标记类型,匹配则显示,否则隐藏。
  • 数据保持不变:所有图层共享同一数据源,切换标记时不会改变数据加载或处理逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 01:32:28