0

I want to plot a function interactively (i.e. the function has a parameter that can change) using Vega or Vega-Lite. As far as I can tell the data parameter can only be from a file or object.

Obviously I can recreate the entire graph/spec every time the function parameter changes, but I'd rather just update the data, so the entire graph doesn't need to be re-rendered. Is there a way to do that?

My function is too complex for Vega's built-in expression system so please don't suggest that.

1 Answer 1

2

You can do this using the Vega view API. Here is an example of a script that inserts dynamically-generated data into a Vega-Lite chart:

var spec = {
  $schema: 'https://vega.github.io/schema/vega-lite/v3.json',
  data: {name: 'table'},
  width: 400,
  mark: 'line',
  encoding: {
    x: {field: 'x', type: 'quantitative', scale: {domain: [0, 100]}},
    y: {field: 'y', type: 'quantitative', scale: {domain: [-1, 1]}}
  }
};

function makeData(N) {
  data = [];
  for (x = 0; x < N; x++) {
    data.push({x: x, y: Math.sin(x / 10)})
  }
  return data
}

vegaEmbed('#chart', spec).then(function(res) {
  var changeSet = vega.changeset().insert(makeData(100));
  res.view.change('table', changeSet).run();
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vega/5.7.0/vega.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vega-lite/3.4.0/vega-lite.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vega-embed/5.1.3/vega-embed.js"></script>
<div id="chart"></div>

Sign up to request clarification or add additional context in comments.

1 Comment

I had to do vega.changeset().remove(() => true).insert(data); otherwise it doesn't remove all the old data when adding more.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.