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

Vega Lite饼图图例表格化格式配置技术咨询

解决方案:Vega Lite 饼图实现表格样式图例

Vega Lite 的原生图例组件无法直接实现表格式的排版布局,但可以通过图层(Layer)+ 自定义标记的方式模拟表格图例,实现字段名、数值的对齐显示,且能自适应文本长度变化。

核心思路

通过图层将饼图与自定义图例组件分离:

  • 第一层绘制饼图主体
  • 第二层使用 rect 标记绘制颜色方块,text 标记分别渲染字段名和数值,通过固定列的 x 坐标实现对齐排版

完整代码实现

{
  "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
  "description": "Pie chart with table-style legend",
  "data": {
    "values": [
      {"category": "Field1", "value": 40},
      {"category": "Field2", "value": 36},
      {"category": "Field3", "value": 10},
      {"category": "Field4", "value": 9},
      {"category": "Field5", "value": 4},
      {"category": "Field6", "value": 1}
    ]
  },
  "layer": [
    // 饼图主体层
    {
      "mark": {"type": "arc", "radius": 120},
      "encoding": {
        "theta": {"field": "value", "type": "quantitative"},
        "color": {
          "field": "category",
          "type": "nominal",
          "sort": false,
          "legend": null // 关闭原生图例
        }
      }
    },
    // 自定义表格图例:颜色方块
    {
      "data": {"name": "source"},
      "mark": {"type": "rect", "width": 20, "height": 20},
      "encoding": {
        "x": {"value": 300},
        "y": {
          "field": "category",
          "type": "nominal",
          "sort": false,
          "axis": null,
          "band": 0.8
        },
        "fill": {"field": "category", "type": "nominal", "sort": false}
      }
    },
    // 自定义表格图例:字段名文本
    {
      "data": {"name": "source"},
      "mark": {"type": "text", "x": 330, "align": "left", "baseline": "middle", "fontSize": 18, "font": "Arial Narrow"},
      "encoding": {
        "y": {
          "field": "category",
          "type": "nominal",
          "sort": false,
          "axis": null,
          "band": 0.8
        },
        "text": {"field": "category"}
      }
    },
    // 自定义表格图例:数值文本(右对齐保证排版规整)
    {
      "data": {"name": "source"},
      "mark": {"type": "text", "x": 450, "align": "right", "baseline": "middle", "fontSize": 18, "font": "Arial Narrow"},
      "encoding": {
        "y": {
          "field": "category",
          "type": "nominal",
          "sort": false,
          "axis": null,
          "band": 0.8
        },
        "text": {"field": "value"}
      }
    }
  ],
  "config": {"view": {"stroke": null}}
}

关键配置说明

  1. 关闭原生图例:在饼图的颜色编码中设置 "legend": null,避免和自定义图例冲突
  2. 列定位:通过 x 固定值划分三列,可根据需求调整数值:
    • 颜色方块列:x: 300
    • 字段名列:x: 330(与颜色方块间隔30px)
    • 数值列:x: 450,设置 align: "right" 实现右对齐,确保不同长度的数值自动对齐
  3. 行对齐:三个图例组件共享相同的 y 编码配置,保证每行的颜色块、字段名、数值垂直对齐
  4. 自适应排版:数值列右对齐、字段名列左对齐的设置,可让文本长度变化时仍保持表格式规整布局

效果调整建议

  • 修改 x 的固定值可调整列间距和图例整体位置
  • 修改 rect 的 width/height 属性可调整颜色方块大小
  • 调整 text 标记的 fontSize/font 属性可匹配需求样式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 13:26:01