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

Vega-Lite人口金字塔动态设置X轴统一最大域问题

解决Vega-Lite人口金字塔两侧X轴动态同步最大值问题

当前基于官方人口金字塔示例开发图表时,男女分图的X轴上限是独立计算的,导致两侧刻度不一致,容易误导数据分布判断。由于需要通过切片器过滤数据集,必须动态将两侧X轴设置为男女各年龄段人口总和的最大值。之前尝试用joinaggregate计算MaxVal并应用到scale.domain但未生效,核心原因是domain或domainMax无法直接引用字段名,必须通过表达式获取动态计算值。

修正后的代码

{
  "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
  "description": "2000年美国人口金字塔",
  "data": { "url": "data/population.json"},
  "transform": [
    {"filter": "datum.year == 2000"},
    {"calculate": "datum.sex == 2 ? 'Female' : 'Male'", "as": "gender"},
    // 按性别+年龄段分组求和,得到各分组的人口总数
    {"aggregate": [{"op": "sum", "field": "people", "as": "age_total"}], "groupby": ["gender", "age"]},
    // 全局计算所有分组人口数的最大值
    {"joinaggregate": [{"op": "max", "field": "age_total", "as": "MaxVal"}]}
  ],
  "spacing": 0,
  "hconcat": [{
    "transform": [{
      "filter": {"field": "gender", "equal": "Female"}
    }],
    "title": "女性",
    "mark": "bar",
    "encoding": {
      "y": {
        "field": "age", "axis": null, "sort": "descending"
      },
      "x": {
        "field": "age_total",
        "title": "人口数",
        "axis": {"format": "s"},
        "scale": {"domainMax": {"expr": "data('source_0')[0].MaxVal"}},
        "sort": "descending"
      },
      "color": {
        "field": "gender",
        "scale": {"range": ["#675193", "#ca8861"]},
        "legend": null
      }
    }
  }, {
    "width": 20,
    "view": {"stroke": null},
    "mark": {
      "type": "text",
      "align": "center"
    },
    "encoding": {
      "y": {"field": "age", "type": "ordinal", "axis": null, "sort": "descending"},
      "text": {"field": "age", "type": "quantitative"}
    }
  }, {
    "transform": [{
      "filter": {"field": "gender", "equal": "Male"}
    }],
    "title": "男性",
    "mark": "bar",
    "encoding": {
      "y": {
        "field": "age", "title": null,
        "axis": null, "sort": "descending"
      },
      "x": {
        "field": "age_total",
        "title": "人口数",
        "axis": {"format": "s"},
        "scale": {"domainMax": {"expr": "data('source_0')[0].MaxVal"}}
      },
      "color": {
        "field": "gender",
        "legend": null
      }
    }
  }],
  "config": {
    "view": {"stroke": null},
    "axis": {"grid": false}
  }
}

关键修改说明

  1. 调整数据转换逻辑:先通过aggregate按性别和年龄段分组计算人口总和,再用joinaggregate全局提取所有分组中的最大值,确保MaxVal是男女各年龄段的峰值。
  2. 动态绑定轴上限:使用scale.domainMax配合表达式{"expr": "data('source_0')[0].MaxVal"},直接引用全局计算出的最大值,实现过滤数据后轴上限自动更新。
  3. 移除重复聚合:将X轴的聚合逻辑提前到全局转换中,避免编码层重复计算导致的逻辑冲突,同时简化编码结构。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 12:15:11