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

Vega-Lite教程:如何将单列数据拆分为多行展示

解决方法

要将单列月份数据拆分为每行3个的多行布局,你可以通过添加计算字段分组月份,结合Vega-Lite的坐标编码实现目标排列。以下是具体方案:

1. 核心思路

为每个月份计算对应的行号和列号:

  • 先获取月份在全年中的索引(0-11)
  • 行号:通过floor(索引/3)得到(0-3,共4行)
  • 列号:通过索引%3得到(0-2,每行3列)

2. 修改后的完整代码

{
  "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
  "data": {
    "values": [
      {"month": "Jan"}, {"month": "Feb"}, {"month": "Mar"}, {"month": "Apr"}, {"month": "May"}, {"month": "Jun"},
      {"month": "Jul"}, {"month": "Aug"}, {"month": "Sep"}, {"month": "Oct"}, {"month": "Nov"}, {"month": "Dec"}
    ]
  },
  "transform": [
    {
      "calculate": "indexof(['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'], datum.month)",
      "as": "monthIndex"
    },
    {
      "calculate": "floor(datum.monthIndex / 3)",
      "as": "row"
    },
    {
      "calculate": "datum.monthIndex % 3",
      "as": "col"
    }
  ],
  "mark": {"type": "text", "size": 14, "align": "center"},
  "encoding": {
    "x": {
      "field": "col",
      "type": "ordinal",
      "axis": {"hidden": true},
      "scale": {"domain": [0,1,2]}
    },
    "y": {
      "field": "row",
      "type": "ordinal",
      "axis": {"hidden": true},
      "scale": {"domain": [0,1,2,3]}
    },
    "text": {"field": "month", "type": "nominal"}
  },
  "config": {
    "view": {"stroke": "transparent", "padding": 10}
  }
}

效果说明

  • 月份将自动按Jan Feb Mar、Apr May Jun等每行3个的格式排列
  • 隐藏了坐标轴,仅保留纯文本布局
  • 可通过调整mark.size、view.padding等参数优化样式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 19:09:29