如何根据 Vega-Lite API 中的值进行条件着色

How do I do conditional coloring based on a value in the Vega-Lite API

我正在尝试使用此页面上相同样式的黑白文本有条件地为热图文本着色:Condition

我正在专门查看条件颜色编码:

 "encoding": {
        "text": {"field": "num_cars", "type": "quantitative"},
        "color": {
          "condition": {"test": "datum['num_cars'] < 40", "value": "black"},
          "value": "white"
        }
      }

我似乎无法获得类似于在 Vega-Lite 中工作的东西。我的最新版本如下所示:

vl.data(weatherData)
  .transform(
    vl.calculate("monthAbbrevFormat(month(datum.date))").as("month"),
    vl.calculate("date(datum.date)").as("day"),
    vl.aggregate([{op:"average",
      field:"temp_max",
      as:"avg_temp"
    }]).groupby(["month","day"])
  )
  .encode(
    vl.y().fieldO("month").sort(["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]),
    vl.x().fieldO("day")
    )
  .layer(
  vl.markRect({tooltip: true, clip: true})
  .encode(
    vl.color().average("avg_temp").scale({scheme:"redyellowblue", reverse:true})
  ),
  vl.markText({tooltip: true, clip: true})
  .encode(
    vl.text().average("avg_temp").format(".1f"),
    vl.color().condition({test:"datum['avg_temp'] > 26",value:"white"}).value("black")
  )
)

  .width(1000)
  .height(400)
.render()

当我将其转换为 JSON 时,我得到


"color":{
  "condition":{"test":"datum['avg_temp'] > 26", "value":"white"},
  "value":"black"
}

这在我看来是一样的。不过文字坚决留黑

我已经将输出 JSON 放入 Vega 编辑器中,但它在那里也不起作用,所以问题不仅限于我使用 JavaScript API.如果有人能指出我的逻辑失败的地方(并在 API 中填写正确的语法,因为遗憾的是文档中缺少示例),那就太好了。

我想通了我的问题。在早期版本中,我计算编码中的平均值。我切换到在转换中预先计算它,并且没有更新文本的编码。所以还是

.encode(
    vl.text().average("avg_temp").format(".1f"),
    vl.color().condition({test:"datum['avg_temp'] > 26",value:"white"}).value("black")
  )

average 没有更改值,但这意味着 dataum['avg_temp'] 不可用。

如果有一种方法可以将平均值作为测试的一部分进行计算,那会使它变得更清晰,但我找不到方法来做到这一点。