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

Vega-Lite三字段柱状图展示问题:单柱+重叠柱布局调整

Vega-Lite 三字段分组布局解决方案

要实现Expected(橙色柱)独立显示,Actual与PlusQuatation重叠显示且按月分组的效果,你需要调整x轴的分组逻辑,结合图层叠加来实现。以下是修正后的配置:

{
  "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
  "data": { "name": "dataset" },
  "transform": [
    // 为每个数据项添加分组标识:区分Expected和组合组(Actual/PlusQuatation)
    {
      "calculate": "datum.Expected !== undefined ? 'Expected' : 'Combined'",
      "as": "Group"
    }
  ],
  "encoding": {
    "x": {
      // 按月份+分组字段构建x轴,实现每月两个分组
      "field": "Date",
      "type": "temporal",
      "timeUnit": "month",
      "title": "Month",
      "axis": {"format": "%b"},
      "scale": {"padding": 0.2},
      "band": 0.8 // 控制月份分组的宽度
    },
    "xOffset": {
      // 用分组字段控制偏移,让同一月份内的两个分组并排
      "field": "Group",
      "type": "nominal",
      "scale": {"range": [-0.3, 0.3]} // 调整偏移范围控制分组间距
    }
  },
  "layer": [
    // 绘制PlusQuatation(绿色),与Actual重叠
    {
      "mark": {"type": "bar", "color": "green", "opacity": 0.7},
      "encoding": {
        "y": {"field": "PlusQuatation", "type": "quantitative"},
        // 仅在Combined分组显示
        "filter": "datum.Group === 'Combined'"
      }
    },
    // 绘制Actual(蓝色),与PlusQuatation重叠
    {
      "mark": {"type": "bar", "color": "blue", "opacity": 0.7},
      "encoding": {
        "y": {"field": "Actual", "type": "quantitative", "title": "Values"},
        "filter": "datum.Group === 'Combined'"
      }
    },
    // 绘制Expected(橙色),独立显示
    {
      "mark": {"type": "bar", "color": "orange"},
      "encoding": {
        "y": {"field": "Expected", "type": "quantitative"},
        "filter": "datum.Group === 'Expected'"
      }
    }
  ],
  "title": "Actual, Expected, and PlusQuatation over Time",
  "config": {
    "axis": {"titleFontSize": 12, "labelFontSize": 10},
    "legend": {"orient": "bottom", "labelFontSize": 10}
  },
  "width": 800
}

关键调整说明

  • 分组字段构造:通过transform添加Group字段,将数据分为Expected和Combined两类,为x轴分组提供依据。
  • x轴分组与偏移:x轴基于月份+分组字段构建,配合xOffset实现同一月份内两个分组的并排布局,scale.range控制分组间距。
  • 图层过滤:每个图层通过filter控制仅在对应分组显示,确保Actual和PlusQuatation仅在Combined分组重叠,Expected独立显示。
  • 透明度调整:给重叠的柱添加opacity,方便同时查看两个数值的对比。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 14:12:17