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

Vega-Lite Strip Plot添加分类计数右侧数据标签问题求助

Vega-Lite带状图添加分类数量标签解决方案

我尝试在Vega-Lite绘制的带状图中统计每个分类的数量,并在图表右侧显示对应数据标签,参考示例图实现后未成功,原始代码如下:

{
  "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
  "width": 400, "height": 100,
  "data": {
          "url": "data/cars.json"

   },
  "encoding": {
     "x": {"field": "Horsepower", "type": "quantitative"},
     "y": {"field": "Origin","axis": {"titleColor": "#6F4ACB"}},
     "color": {
     "condition": {"test": "datum['Horsepower'] < 60", "value": "#B4AEE8"},
     "value": "#6F4ACB"
 }
 },
"layer": [
    {
      "mark": {"opacity": 0.9, "type": "circle", "color": "#6F4ACB", "size":200}
    },
    {
     "mark": {"type": "text", "x": -2, "align": "right"},
      "transform": [
       {
         "aggregate": [{"op": "count", "field": "Name", "as": "lo"}],
         "groupby": ["Origin"]
       }
     ],
      "encoding": {
      "text": {"field": "lo"}
    }
   }
 ]
}

修正后的代码

{
  "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
  "width": 400, "height": 100,
  "data": {
          "url": "data/cars.json"
   },
  "encoding": {
     "x": {"field": "Horsepower", "type": "quantitative"},
     "y": {"field": "Origin","axis": {"titleColor": "#6F4ACB"}},
     "color": {
     "condition": {"test": "datum['Horsepower'] < 60", "value": "#B4AEE8"},
     "value": "#6F4ACB"
 }
 },
"layer": [
    {
      "mark": {"opacity": 0.9, "type": "circle", "size":200}
    },
    {
     "mark": {"type": "text", "x": 410, "align": "left"},
      "transform": [
       {
         "aggregate": [{"op": "count", "field": "Name", "as": "count"}],
         "groupby": ["Origin"]
       }
     ],
      "encoding": {
        "y": {"field": "Origin", "type": "nominal"},
        "text": {"field": "count", "type": "quantitative"}
      }
   }
 ]
}

关键修改说明

  • 调整文本标记位置:将x设为410(略大于图表宽度400),align设为left,让数量标签显示在图表右侧。
  • 绑定文本层y轴编码:添加y: {"field": "Origin", "type": "nominal"},确保每个分类的数量标签和对应行对齐。
  • 修复颜色逻辑:移除圆形标记的硬编码color,让顶层的条件颜色规则正常生效。
  • 优化字段命名:将聚合结果字段从lo改为count,语义更清晰。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 00:22:05