【问题标题】:How to set the Data Source in a VEGA barchart?如何在 VEGA 条形图中设置数据源?
【发布时间】:2021-03-02 14:15:27
【问题描述】:

我正在关注basic VEGA tutorial where a Barchart is rendered。 只要所有数据都在第一次加载的 JSON 设置文件中,这种方法就可以工作。但是教程中说数据源也可以这样设置:

  • 使用 url 属性从 Web 加载(包括 JSON 和 CSV 文件),
  • 使用源属性从先前定义的数据集派生,或
  • 在构建可视化时未定义并动态设置

我将选择最后一个选项,在我的 javascript 文件中设置数据。但我的尝试都没有奏效。不呈现数据。如何在 VEGA 图表中动态设置数据源?

我的代码

let testData = [
    {"category": "A","amount": 66},
    {"category": "B","amount": 33}
]


fetch('tablespecs.json')
    .then(res => res.json())
    .then(spec => render(spec))
    .catch(err => console.error(err))


function render(spec) {
    let view = new vega.View(vega.parse(spec), {
        renderer: 'canvas',                 
        container: '#view',                
        hover: true,
        source:testData                       // not working
    })

    view.source = testData                    // not working
    view.data.source = testData               // not working
    view.data = testData                      // not working

    view.runAsync()
}

表格规格直接从教程页面复制而来。我刚刚忽略了values 属性。我还尝试省略整个 data 属性。

规格 JSON

{
    "$schema": "https://vega.github.io/schema/vega/v5.json",
    "width": 400,
    "height": 200,
    "padding": 5,
    "data": [
        {
            "name": "table",
            // removed values here
        }
    ],
    // ... rest of barchart specs unchanged from example
}

【问题讨论】:

  • 你有没有找到解决这个问题的办法。我也面临同样的问题。

标签: javascript vega


【解决方案1】:

我怀疑您的问题可能与在将结果注入视图之前没有等待结果有关。下面的代码用于在视图渲染后更新数据。确保包含此代码的函数被标记为异步。

 await this.view.change('table', vega.changeset().remove(vega.truthy).insert(
      [
        {'category': 'A', 'amount': 21},
        {'category': 'B', 'amount': 551},
        {'category': 'C', 'amount': 471},
        {'category': 'D', 'amount': 91},
        {'category': 'E', 'amount': 85},
        {'category': 'F', 'amount': 211},
        {'category': 'G', 'amount': 91},
        {'category': 'H', 'amount': 74}
      ]
    )).runAsync();

来源:https://vega.github.io/vega/docs/api/view/#data-and-scales

【讨论】:

    猜你喜欢
    • 2016-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-22
    • 1970-01-01
    • 1970-01-01
    • 2016-05-28
    相关资源
    最近更新 更多