何时在“层”与“顶级Vega-lite”规范中嵌套标记属性?

问题描述

我想知道Vega-lite如何将标记与关联的编码相关联。

在下面的示例中,编码和标记均位于规范的“顶层”:

{
  "$schema": "https://vega.github.io/schema/vega-lite/v4.json","description": "A simple bar chart with embedded data.","data": {
    "values": [
      {"a": "A","b": 28},{"a": "B","b": 55},{"a": "C","b": 43},{"a": "D","b": 91},{"a": "E","b": 81},{"a": "F","b": 53},{"a": "G","b": 19},{"a": "H","b": 87},{"a": "I","b": 52}
    ]
  },"mark": "bar","encoding": {
    "x": {"field": "a","type": "nominal","axis": {"labelAngle": 0}},"y": {"field": "b","type": "quantitative"}
  }
}

在最简单的图层示例中,条形标记和文本标记都嵌套在Layer属性

{
  "$schema": "https://vega.github.io/schema/vega-lite/v4.json","description": "Bar chart with text labels. Apply scale padding to make the frame cover the labels.","b": 43}
    ]
  },"encoding": {
    "y": {"field": "a","type": "nominal"},"x": {"field": "b","type": "quantitative","scale": {"padding": 10}}
  },"layer": [{
    "mark": "bar"
  },{
    "mark": {
      "type": "text","align": "left","baseline": "middle","dx": 3
    },"encoding": {
      "text": {"field": "b","type": "quantitative"}
    }
  }]
}

Vega-lite文档对这些属性的配置进行了相当详细的介绍,但我无法找到这三个问题的概念性答案。

谢谢

解决方法

Vega-Lite提供了一个层次结构的图表模型,其中层次结构中的每个级别都可以覆盖父级别中声明的各种属性。在层规范方面,相关概念是这样的:

  • 您认为UnitSpec是一张图表:您可以指定datamarkencodingstransforms和其他属性。
  • LayerSpec是一个容器,可以在UnitSpec属性中容纳许多LayerSpeclayers规范。此外,您可以指定dataencodings transforms和其他属性(但不能指定mark)。

UnitSpec或其他顶级对象中的LayerSpec将继承在那里指定的任何属性(例如dataencodingstransforms等),还可以通过指定自己的dataencodingstransforms覆盖它们。

类似的层次结构概念也适用于其他复合图表类型,例如ConcatSpecVConcatSpecHConcatSpecFacetSpec等。

更具体地说,在您的示例中,data和某些encodings在顶层中定义:

{
  "$schema": "https://vega.github.io/schema/vega-lite/v4.json","description": "Bar chart with text labels. Apply scale padding to make the frame cover the labels.","data": {
    "values": [
      {"a": "A","b": 28},{"a": "B","b": 55},{"a": "C","b": 43}
    ]
  },"encoding": {
    "y": {"field": "a","type": "nominal"},"x": {"field": "b","type": "quantitative","scale": {"padding": 10}}
  },"layer": [{
    "mark": "bar"
  },{
    "mark": {
      "type": "text","align": "left","baseline": "middle","dx": 3
    },"encoding": {
      "text": {"field": "b","type": "quantitative"}
    }
  }]
}

就从父级继承而言,这在功能上等效于以下内容,其中我将dataencodings从顶层移到了每个包含的UnitSpec中:>

{
  "$schema": "https://vega.github.io/schema/vega-lite/v4.json","layer": [{
    "data": {
      "values": [
        {"a": "A","b": 43}
      ]
    },"mark": "bar"
    "encoding": {
      "y": {"field": "a","scale": {"padding": 10}}
    },},{
    "data": {
      "values": [
        {"a": "A","mark": {
      "type": "text","encoding": {
      "y": {"field": "a","scale": {"padding": 10}}
      "text": {"field": "b","type": "quantitative"}
    }
  }]
}

在顶层指定共享属性是一种使图表规范更加简洁和易于理解的方法。