RobinL
RobinL

Reputation: 11587

Display vega spec in Jupyter Lab

How can I display a vega spec (such as this force directed layout) in Jupyter Lab/JupyterLab?

Upvotes: 2

Views: 349

Answers (1)

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)

Alternatively, you can use Vega Embed through the javascript extension:

Add the scripts:

%%javascript
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = '//cdn.jsdelivr.net/npm/vega@5';
    document.head.appendChild(script);
    
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = '//cdn.jsdelivr.net/npm/vega-embed@6';
    document.head.appendChild(script);

then

from IPython.display import Javascript
script = '''
var spec = "https://raw.githubusercontent.com/vega/vega/master/docs/examples/bar-chart.vg.json";
vegaEmbed(element, spec).then(function(result) {
  }).catch(console.error);  
'''

Javascript(script)

Note: The example force directed spec at https://raw.githubusercontent.com/vega/vega/master/docs/examples/force-directed-layout.vg.json doesn't display because it references data at a relative url (data/miserables.json). The bar chart works because the data is encoded directly into the spec.

Upvotes: 2

Related Questions