首页 > 解决方案 > 如何在 Vega-Lite 中格式化货币?

问题描述

我正在尝试在 Vega-Lite 编辑器中将值格式化为货币。我正在尝试复制文档,但遇到了一个奇怪的错误。Y轴是数值。传入格式化字符串会给出“预期值”。

这是json:

{
  "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
  "description": "Protocol Chart",
  "width": 500,
  "height": 225,
  "data": {
        "values": [
        {
            "asset": "eth",
            "time": "2021-06-15T00:00:00Z",
            "ReferenceRateUSD": "2577.04473863238"
        },
        {
            "asset": "eth",
            "time": "2021-06-16T00:00:00Z",
            "ReferenceRateUSD": "2552.74103641146"
        },
        {
            "asset": "eth",
            "time": "2021-06-17T00:00:00Z",
            "ReferenceRateUSD": "2360.99938690824"
        }
    ]
  },
  "config": {
        "view": {
            "stroke": "transparent"
        }
  },
  "mark": "line",
    "encoding": {
        "x": {
            "axis": {
                "domainColor": "#DDD",
                "grid": false, 
                "labelColor": "#AEAEAE", 
                "ticks": false, 
                "labelPadding": 10
            }, 
            "field": "time", 
            "type": "temporal", 
            "title": ""
        },
        "y": {
            "axis": {
                "labelOffset": 2,
                "domainColor": "white",
                "labelColor": "#AEAEAE", 
                "ticks": false, 
                "labelPadding": 10,
                "format": '$.2f'
            }, 
            "field": "ReferenceRateUSD", 
            "type": "quantitative", 
            "title": "", 
            "scale": {
                "zero": false
            }
        },
        "color": {
            "field": "doesntmatter", 
            "type": "nominal", 
            "legend": null,
            "scale": {
                "range": ["#91DB97"]
            }
        }
  }
}

我在这里想念什么?如何让它接受我的格式字符串?

标签: data-visualizationvega-litevega

解决方案


"$.2f"看起来像货币的正确d3 格式formatType字符串,但请注意,这仅在关联为时才有效"number"(请参阅轴标签文档)。

由于您没有包含您所看到问题的完整可重现示例,因此我只能冒险猜测您的数据类型不是数字,这就是格式化失败的原因。如果不是这种情况,我建议您编辑您的问题,以提供您所看到的错误的完整示例。


编辑:您的完整示例似乎可以与当前版本的 vega/vega-lite 正常工作(在编辑器中查看):

在此处输入图像描述

也许您需要更新您的 vega/vega-lite 库?


推荐阅读