Timmmm
Timmmm

Reputation: 96586

Plot data from javascript function using Vega

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.

Upvotes: 0

Views: 698

Answers (1)

jakevdp
jakevdp

Reputation: 86330

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>

Upvotes: 2

Related Questions