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

如何在Vega-Lite图表中移除无数据年份并优化边缘显示

Vega-Lite图表优化方案

解决无数据年份显示问题

将x轴的temporal类型改为ordinal,图表会只渲染数据中实际存在的年份,自动剔除无数据的2021年:

  • 修改encoding.x.type为ordinal

优化图表边缘内容溢出

通过调整x轴缩放内边距和柱状图宽度,避免首尾年份内容超出边界:

  • 给x轴的scale添加padding参数(示例设为0.2),增加年份两侧的空白
  • 调整柱状图width,将band:1改为band:0.8,让柱状图之间保留间隔,同时不撑满图表边界

修改后的完整代码

{
  "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
  "data": {"url": "https://raw.githubusercontent.com/sebastipasti/seba27.github.io/refs/heads/main/VA%20tinker.csv"},
  "mark": {"type": "bar", "width": {"band": 0.8}, 
  "cornerRadiusEnd": 2},
  "encoding": {
    "x": {
      "field": "Year",
      "type": "ordinal",
      "axis": {"domain": false, "grid": false},
      "scale": {"nice": false, "zero": false, "padding": 0.2},
      "title": "Year"
    },
    "y": {
      "field": "Value",
      "type": "quantitative",
      "axis": {"domain": false, "grid": false, "offset": 20},
      "title": null
    },
    "xOffset": {"field": "Group"},
    "color": {
      "field": "Group",
      "type": "nominal",
      "scale": {
        "domain": ["Violence against the person", "Rape", "Sexual offences", "Robbery", "Theft offences", "Criminal damage and arson", "Drug offences", "Possession of weapons", "Public order offences", "Miscellaneous crimes against society", "Fraud offences"],
        "range": ["#9e0142", "#d53e4f", "#f46d43", "#fdae61", "#fee08b", "#ffffbf", "#e6f598", "#abdda4", "#66c2a5", "#3288bd", "#5e4fa2"]
      },
      "title": "Offence Group"
    },
    "order": {"field": "order", "type": "ordinal"}
  },
  "resolve": {"scale": {"x": "independent"}}
}

关键修改说明

  1. x轴类型调整:从temporal改为ordinal,仅展示数据中存在的年份,自动隐藏无数据的2021年
  2. 柱状图宽度优化:width: {"band": 0.8}降低柱状图占比,避免撑满边界
  3. x轴内边距:scale.padding: 0.2给首尾年份添加空白,防止内容溢出

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 19:51:10