Skip to content

Instantly share code, notes, and snippets.

@simonw
Created June 24, 2018 00:21
Show Gist options
  • Save simonw/7e4b21d0f3cc1d17eaa314fb3f904843 to your computer and use it in GitHub Desktop.
Save simonw/7e4b21d0f3cc1d17eaa314fb3f904843 to your computer and use it in GitHub Desktop.
How to update an existing vega view with new fetched data

How to update an existing vega view with new fetched data

This took quite a bit of figuring out because the web is littered with Vega 2 examples but Vega 3 is a bit different.

https://vega.github.io/vega/docs/api/view/#view_change

var spec = {
  data: {"url": "https://fivethirtyeight.datasettes.com/fivethirtyeight-45d758d/most-common-name%2Fsurnames.json?_shape=array"},
  mark: "bar",
  encoding: {
    x: {field: "name", type: "ordinal"},
    y: {field: "count", type: "quantitative"}
  }
};

// Embed visualization and save view as window.view:
vegaEmbed("#vis", vlSpec).then(p => window.view = p.view);

// Then later...
fetch(
  "https://fivethirtyeight.datasettes.com/fivethirtyeight-45d758d/most-common-name%2Fsurnames.json?_shape=array&_size=30"
).then(r => r.json()).then(data => {
  // Changeset needs to remove everything first, then insert new data
  let changeset = vega.changeset().remove(() => true).insert(data);
  // For some reason source_0 is the default dataset name
  view.change('source_0', changeset).run()
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment