如何在 VegaLite 中指定具有单个值的规则线?

How to specify Rule Line with a single value in VegaLite?

可以将规则指定为对数据的编码。但有时它太冗长了。有没有更短的方法可以只用一个数字来指定它?

在下面的示例中,我想用 y=1 绘制一条水平线,它需要我指定一个计算转换。想知道是否可以使用更紧凑的东西,例如:

"layer": [
  ...,
  { "mark": { "type": "rule", "y": 1 }, // Specify ruler with just a single line
  ...
]

Playground

{
  "$schema": "https://vega.github.io/schema/vega-lite/v4.json",
  "transform":[
    { "calculate": "1", "as": "one" }
  ],
  "layer": [
    {
      "mark": { "type": "bar" },
      "encoding": {
        "x": { "field": "diff", "type": "quantitative" },
        "y": { "field": "diff", "type": "quantitative" }
      }
    },
    {
      "mark": { "type": "rule" },
      "encoding": {
        "y": { "field": "one", "type": "quantitative" }
      }
    }
  ],
  "data": {
    "values": [
      { "diff": 1 },
      { "diff": 2 },
      { "diff": 3 }
    ]
  }
}

您可以在编码中使用 "value" 字段指定单个值;例如

{
  "mark": { "type": "rule" },
  "encoding": {
    "y": { "value": 133 }
  }
}

(Playground)

但请注意,此值是 轴域 中的值,而不是数据域中的值;即它代表图表左上角的像素。

如果要指定数据域中的值,则没有shorthand。您必须使用转换(就像您在问题中所做的那样)或为您的图层定义一个新的数据集。我认为最紧凑的方式是这样的:

{
  "mark": { "type": "rule" },
  "data": {"values": {"y": 1}},
  "encoding": {
    "y": { "field": "y" }
  }
}