首页 > 解决方案 > Vega-lite 以 SI 单位显示文本值

问题描述

我的示例源代码如下

{
  "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
  "description": "A simple bar chart with embedded data.",
  "data": {
    "values": [
      {"a": "A", "b": 28000}, {"a": "B", "b": 55000}, 
      {"a": "C", "b": 43000}, {"a": "D", "b": 91000}, 
      {"a": "E", "b": 81000}, {"a": "F", "b": 53000},
      {"a": "G", "b": 19000}, {"a": "H", "b": 87000}, 
      {"a": "I", "b": 52000}
    ]
  },
    "encoding": {
    "x": {"field": "a", "type": "nominal", "axis": {"labelAngle": 0}},
    "y": {"field": "b", "type": "quantitative"}
  },
  "layer": [{
    "mark": "bar"
  },
  {
    "mark":{
       "type":"text",
       "align":"center",
       "baseline":"middle",
       "dx":0,
       "dy":-5
    } ,
    "encoding":{
       "text":{"field":"b","type":"quantitative"}
    }
  }
  ]
}

我希望文本标记以 SI 单位动态显示。所以在我的例子中,28k, 55k,43k等等。

我怎样才能在 Vega-lite 中做到这一点?

标签: vega-lite

解决方案


在您的文本中添加格式化程序,如下所示或在编辑器中:

{
  "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
  "description": "A simple bar chart with embedded data.",
  "data": {
    "values": [
      {"a": "A", "b": 28000},
      {"a": "B", "b": 55000},
      {"a": "C", "b": 43000},
      {"a": "D", "b": 91000},
      {"a": "E", "b": 81000},
      {"a": "F", "b": 53000},
      {"a": "G", "b": 19000},
      {"a": "H", "b": 87000}
    ]
  },
  "encoding": {
    "x": {"field": "a", "type": "nominal", "axis": {"labelAngle": 0}},
    "y": {"field": "b", "type": "quantitative"}
  },
  "layer": [
    {"mark": "bar"},
    {
      "mark": {
        "type": "text",
        "align": "center",
        "baseline": "middle",
        "dx": 0,
        "dy": -5
      },
      "encoding": {
        "text": {"field": "b", "type": "quantitative", "format": ".2s"}
      }
    }
  ]
}

编辑

要在不同的值范围上提供不同的格式,您可以简单地执行calculate转换并根据条件创建格式化的值。然后,只需使用 value 字段,text如下所示或参考editor

{
  "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
  "description": "A simple bar chart with embedded data.",
  "data": {
    "values": [
      {"a": "A", "b": 28000},
      {"a": "B", "b": 55000},
      {"a": "C", "b": 43000},
      {"a": "D", "b": 91000},
      {"a": "E", "b": 81000},
      {"a": "F", "b": 53000},
      {"a": "G", "b": 19000},
      {"a": "H", "b": 87000},
      {"a": "I", "b": 523399}
    ]
  },
  "transform": [
    {
      "calculate": "datum.b > 99999 ? format(datum.b,'.3s') : format(datum.b,'.2s')",
      "as": "textValue"
    }
  ],
  "encoding": {
    "x": {"field": "a", "type": "nominal", "axis": {"labelAngle": 0}},
    "y": {"field": "b", "type": "quantitative"}
  },
  "layer": [
    {"mark": "bar"},
    {
      "mark": {
        "type": "text",
        "align": "center",
        "baseline": "middle",
        "dx": 0,
        "dy": -5
      },
      "encoding": {"text": {"field": "textValue"}}
    }
  ]
}

您可以参考文档以了解有关数字格式的更多信息或查看github 上的测试文件


推荐阅读