safetyduck
safetyduck

Reputation: 6874

How to embed vega in jupyterlab or notebook?

Am trying to copy paste the example from vega but am getting "vega is not defined" errors.

%%html
<!DOCTYPE html>
<html>
<head>
  <!-- Import Vega 5 & Vega-Lite 3 (does not have to be from CDN) -->
  <script src="https://cdn.jsdelivr.net/npm/vega@[5]"></script>
  <script src="https://cdn.jsdelivr.net/npm/vega-lite@[5]"></script>
  <!-- Import vega-embed -->
  <script src="https://cdn.jsdelivr.net/npm/vega-embed@[5]"></script>
</head>
<body>

<div id="vis"></div>

<script type="text/javascript">
  var spec = "https://raw.githubusercontent.com/vega/vega/master/docs/examples/bar-chart.vg.json";
  vegaEmbed('#vis', spec).then(function(result) {
    // Access the Vega view instance (https://vega.github.io/vega/docs/api/view/) as result.view
  }).catch(console.error);
</script>
</body>
</html>

Is there something special about how jupyterlab treats html/js in the magic that breaks this?

Upvotes: 1

Views: 962

Answers (2)

RobinL
RobinL

Reputation: 11587

If you don't mind installing altair, you can do this:

from altair.vega import vega
import json
with open("bar-chart.vg.json") as f:
    s = json.load(f)
vega(s)

This definitely works in Jupyter Lab, not sure about notebook

Upvotes: 2

teu
teu

Reputation: 979

The "head" declarations won't work in a Jupyter cel. You can try something like this to define vegaEmbed:

<script>
requirejs.config({
  baseUrl: 'https://cdn.jsdelivr.net/npm/',
  paths: {
    "vega-embed":  "vega-embed@5?noext",
    "vega-lib": "vega-lib?@5noext",
    "vega-lite": "vega-lite@4?noext",
    "vega": "vega@5?noext"
  }
});

requirejs(["vega", "vega-embed"], function(vega, vegaEmbed) {
     console.log(vega.version);
     console.log(vegaEmbed.version);
     window.vegaEmbed=vegaEmbed;
     window.vega = vega;});
</script>

Then a cel with just the body HTML should work. (Note: tried this in a regular Jupyter notebook, not Jupyterlab.)

UPDATE:

This works in jupyter notebooks but not in JupyterLab:

%%html
<script>
requirejs.config({
  baseUrl: 'https://cdn.jsdelivr.net/npm/',
  paths: {
    "vega-embed":  "vega-embed@5?noext",
    "vega-lib": "vega-lib?@5noext",
    "vega-lite": "vega-lite@4?noext",
    "vega": "vega@5?noext"
  }
});

requirejs(["vega", "vega-embed"], function(vega, vegaEmbed) {
     console.log(vega.version);
     console.log(vegaEmbed.version);
     window.vegaEmbed=vegaEmbed;
     window.vega = vega;});
</script>

<body>

<div id="vis"></div>

<script type="text/javascript">
  var spec = "https://raw.githubusercontent.com/vega/vega/master/docs/examples/bar-chart.vg.json";
  vegaEmbed('#vis', spec).then(function(result) {
    // Access the Vega view instance (https://vega.github.io/vega/docs/api/view/) as result.view
  }).catch(console.error);
</script>
</body>

Upvotes: 2

Related Questions