Vega-lite:图例标签表达式包含多个字段的值

问题描述 投票:0回答:1

我的代码如下;

{
      "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
      "width": 800,
      "height": 200,
      "data": {
        "values": [
          {
            "pre_120": 0,
            "pre_90": 0,
            "pre_60": 0,
            "post_60": 100,
            "post_90": 150,
            "post_120": 200,
            "type": "Mango",
            "count": "twenty"
          },
          {
            "pre_120": 0,
            "pre_90": 0,
            "pre_60": 0,
            "post_60": 90,
            "post_90": 140,
            "post_120": 190,
            "type": "Apple",
            "count": "ten"
          }
        ]
      },
      "transform": [
        {"fold": ["pre_120", "pre_90", "pre_60","0", "post_60", "post_90", "post_120"]}
      ],
      "layer": [
        {
          "mark": "line",
          "encoding": {
            "x": {
              "field": "key",
              "sort": [
                "pre_120",
                "pre_90",
                "pre_60",
                "0",
                "post_60",
                "post_90",
                "post_120"
              ]
            },
            "y": {"field": "value", "type": "quantitative"},
            "color": {"field": "type", "type": "nominal"}
          }
        },
  {
    "mark": { 
      "type": "rule", 
      "color": "maroon", 
      "size": 3 ,
      "strokeDash": [6, 4]},
    "encoding": {
      "x": { "datum": "0" }
    }
  }
  ]
  }

下面是 vega 编辑器的链接。

https://vega.github.io/editor/#/gist/947b2a99801bc6a08d468cdb9acbeb50/legend.json

我的目标是显示图例包含 2 个字段的值,即带有连字符的 类型和计数字段。 示例:
在下图中,我想将图例显示为
“苹果 - 二十”

“芒果 - 十”
我怎么能做同样的事呢?

javascript charts visualization vega-lite vega
1个回答
2
投票

我只需创建一个新的计算字段并使用它。

{
  "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
  "width": 800,
  "height": 200,
  "data": {
    "values": [
      {
        "pre_120": 0,
        "pre_90": 0,
        "pre_60": 0,
        "post_60": 100,
        "post_90": 150,
        "post_120": 200,
        "type": "Mango",
        "count": "ten"
      },
      {
        "pre_120": 0,
        "pre_90": 0,
        "pre_60": 0,
        "post_60": 90,
        "post_90": 140,
        "post_120": 190,
        "type": "Apple",
        "count": "twenty"
      }
    ]
  },
  "transform": [
    {"fold": ["pre_120", "pre_90", "pre_60", "post_60", "post_90", "post_120"]},
     {"calculate": "datum.type + ' - ' + datum.count", "as": "label"}
  ],
  "layer": [
    {
      "mark": "line",
      "encoding": {
        "x": {
          "field": "key",
          "sort": [
            "pre_120",
            "pre_90",
            "pre_60",
            "post_60",
            "post_90",
            "post_120"
          ]
        },
        "y": {"field": "value", "type": "quantitative"},
        "color": {
          "field": "label",
          "type": "nominal"
        }
      }
    }
  ]
}
© www.soinside.com 2019 - 2024. All rights reserved.