如何在 Vega Lite 中重命名图例标签?

How can I rename legend labels in Vega Lite?

过去几天我一直在尝试重命名我的 vega-lite 图表上的图例标签。

通常这些标签与其各自的数据字段名称相匹配。我有一个案例,我想给它们一个更具描述性的名称,但不重命名原始数据名称。

一个简化的例子:

vl.markLine()
  .data([
    { t:1, v:5, c:'a' }, { t:2, v:3, c:'a' }, { t:3, v:7, c:'a' },
    { t:1, v:6, c:'b' }, { t:2, v:8, c:'b' }, { t:3, v:2, c:'b' }
   ])
  .encode(
    vl.x().fieldQ('t'),
    vl.y().fieldQ('v'),
    vl.color().fieldN('c')
  )
  .render()

如何在不改变原始数据的情况下重命名图例中的'a'和'b'?

(我正在使用 javascript API 但也会对 JSON 解决方案感到满意)。

我想找到一种方法,而不是仅仅为了图例标签而将所有数据复制和映射到另一个变量名。

我还没有找到一种手动输入图例标签的方法,例如“标签”:['long name for a', 'long name for b'].

对此有两种可能的方法。您可以使用 calculate transform to modify the values within the data stream (open in editor):

{
  "data": {
    "values": [
      {"t": 1, "v": 5, "c": "a"},
      {"t": 2, "v": 3, "c": "a"},
      {"t": 3, "v": 7, "c": "a"},
      {"t": 1, "v": 6, "c": "b"},
      {"t": 2, "v": 8, "c": "b"},
      {"t": 3, "v": 2, "c": "b"}
    ]
  },
  "transform": [
    {"calculate": "{'a': 'Label A', 'b': 'Label B'}[datum.c]", "as": "c"}
  ],
  "mark": "line",
  "encoding": {
    "x": {"field": "t", "type": "quantitative"},
    "y": {"field": "v", "type": "quantitative"},
    "color": {"field": "c", "type": "nominal"}
  }
}

或者您可以使用 labelExpr to define new labels, referencing the original label as datum.label (open in editor):

{
  "data": {
    "values": [
      {"t": 1, "v": 5, "c": "a"},
      {"t": 2, "v": 3, "c": "a"},
      {"t": 3, "v": 7, "c": "a"},
      {"t": 1, "v": 6, "c": "b"},
      {"t": 2, "v": 8, "c": "b"},
      {"t": 3, "v": 2, "c": "b"}
    ]
  },
  "mark": "line",
  "encoding": {
    "x": {"field": "t", "type": "quantitative"},
    "y": {"field": "v", "type": "quantitative"},
    "color": {
      "field": "c",
      "type": "nominal",
      "legend": {"labelExpr": "{'a': 'Label A', 'b': 'Label B'}[datum.label]"}
    }
  }
}

前一种方法的好处是它可以更改所有位置的值(包括工具提示等)。后一种方法的好处是效率更高,因为它只对每个唯一标签进行一次转换。