使用 Vega Lite 进行可视化:“emoji undefined”

问题描述

我正在尝试在 Vega Lite (https://vega.github.io/vega-lite/examples/isotype_bar_chart_emoji.html) 中重现可视化效果。我没有选择动物表情符号,而是选择表情符号来象征能源。但是我的代码不起作用,看起来 Vega 无法识别表情符号,因为它标记为:“未定义”。我该如何帮助 vega 使其使用表情符号作为徽标?

{
  "$schema": "https://vega.github.io/schema/vega-lite/v5.json","config": {"view": {"stroke": ""}},"width": 800,"height": 200,"data": {
    "values": [
{"continent": "Africa","share": "coal"},{"continent": "Africa","share": "gas"},{"continent": "Europe","share": "hydro"},"share": "nuclear"},"share": "renewables"},"share": "renewables"}
    ]
  },"transform": [
    {
      "calculate": "{'coal': '?','nuclear': '⚛️','oil': '?️','renewables':'♻️','gas':'⛽'}","as": "emoji"
    },{"window": [{"op": "rank","as": "rank"}],"groupby": ["continent","share"]}
  ],"mark": {"type": "text","baseline": "middle"},"encoding": {
    "x": {"field": "rank","type": "ordinal","axis": null},"y": {"field": "share","type": "nominal","axis": null,"sort": null},"row": {"field": "continent","header": {"title": ""}},"text": {"field": "emoji","type": "nominal"},"size": {"value": 65}
  }
}

解决方法

转换计算不正确,您可以使用 datum 从您的数据访问字段,并根据条件提供 emoji 值。请参阅以下代码或 editor

{
  "$schema": "https://vega.github.io/schema/vega-lite/v5.json","config": {"view": {"stroke": ""}},"width": 800,"height": 200,"data": {
    "values": [
      {"continent": "Africa","share": "coal"},{"continent": "Africa","share": "gas"},{"continent": "Europe","share": "hydro"},"share": "nuclear"},"share": "renewables"},"share": "renewables"}
    ]
  },"transform": [
    {
      "calculate": "datum.share == 'coal' ?  '?' : datum.share == 'nuclear' ? '⚛️' : datum.share == 'oil' ? '?️' : datum.share == 'renewables' ?'♻️' : '⛽'","as": "emoji"
    },{
      "window": [{"op": "rank","as": "rank"}],"groupby": ["continent","share"]
    }
  ],"mark": {"type": "text","baseline": "middle"},"encoding": {
    "x": {"field": "rank","type": "ordinal","axis": null},"y": {"field": "share","type": "nominal","axis": null,"sort": null},"row": {"field": "continent","header": {"title": ""}},"text": {"field": "emoji","type": "nominal"},"size": {"value": 65}
  }
}

或者简单地将这一行添加到您当前的代码中也可以解决问题:

{
  "calculate": "{'coal': '?','nuclear': '⚛️','oil': '?️','renewables':'♻️','gas':'⛽','hydro': '?',}[datum.share]","as": "emoji"
}