为什么在这个 vega-lite 图中编码会像这样分开?

Why are the encodings split up like this in this vega-lite graph?

在这个带有标尺样式工具提示的多线图中,他们将编码分为三层,并将一个层嵌套在外层中。

https://vega.github.io/vega-lite/examples/interactive_multi_line_pivot_tooltip.html

具体来说:

 "encoding": {"x": {"field": "date", "type": "temporal"}},
  "layer": [
    {
      "encoding": {
        "color": {"field": "symbol", "type": "nominal"},
        "y": {"field": "price", "type": "quantitative"}
      },
      "layer": [
        {"mark": "line"},
        {"transform": [{"filter": {"selection": "hover"}}], "mark": "point"}
      ]
    },
    {
      "transform": [{"pivot": "symbol", "value": "price", "groupby": ["date"]}],
      "mark": "rule",
      "encoding": {
        "opacity": {
          "condition": {"value": 0.3, "selection": "hover"},
          "value": 0
        },
        "tooltip": [ ... ],
        "selection": { ... }
      }
    }

首先在定义 x 通道的层之外有一个编码。然后他们在第一层内添加编码,定义 ycolor 通道。然后他们好像在这个外层里面嵌套了一层,然后定义显示出来的点?最后,他们添加了第二层来定义工具提示。

不过我不明白的是

  1. encoding 块在 layers 数组之外的意义所在。这有什么作用?为什么要这样拆分 encoding

  2. 外层里夹着一层,为什么?

文档似乎没有对此进行任何解释。

1) What the point of this encoding block that is outside of the layers array. Whats the effect of this?

层之上的编码被层中的每个子图表继承。

2) Why split up the encoding like this. There's a layer inside an outer layer, why?

您可能会使用这样的多层结构的主要原因是为了避免重复编码规范。您可以通过将所有编码移动到每一层并使用单层语句来创建等效结果,如下所示 (view in editor):

{
  "$schema": "https://vega.github.io/schema/vega-lite/v4.json",
  "data": {"url": "data/stocks.csv"},
  "width": 400,
  "height": 300,
  "layer": [
    {
      "mark": "line",
      "encoding": {
        "x": {"field": "date", "type": "temporal"},
        "y": {"field": "price", "type": "quantitative"},
        "color": {"field": "symbol", "type": "nominal"}
      }
    },
    {
      "transform": [{"filter": {"selection": "hover"}}],
      "mark": "point",
      "encoding": {
        "x": {"field": "date", "type": "temporal"},
        "y": {"field": "price", "type": "quantitative"},
        "color": {"field": "symbol", "type": "nominal"}
      }
    },
    {
      "transform": [{"pivot": "symbol", "value": "price", "groupby": ["date"]}],
      "mark": "rule",
      "encoding": {
        "x": {"field": "date", "type": "temporal"},
        "opacity": {
          "condition": {"value": 0.3, "selection": "hover"},
          "value": 0
        },
        "tooltip": [
          {"field": "AAPL", "type": "quantitative"},
          {"field": "AMZN", "type": "quantitative"},
          {"field": "GOOG", "type": "quantitative"},
          {"field": "IBM", "type": "quantitative"},
          {"field": "MSFT", "type": "quantitative"}
        ]
      },
      "selection": {
        "hover": {
          "type": "single",
          "fields": ["date"],
          "nearest": true,
          "on": "mouseover",
          "empty": "none",
          "clear": "mouseout"
        }
      }
    }
  ]
}

它只是涉及大量重复等效编码。