Skip to content

Instantly share code, notes, and snippets.

@paulroth3d
Last active August 12, 2021 14:13
Show Gist options
  • Save paulroth3d/f2f58146c8a106d9db249a8c3a3f3adc to your computer and use it in GitHub Desktop.
Save paulroth3d/f2f58146c8a106d9db249a8c3a3f3adc to your computer and use it in GitHub Desktop.

Simple use of vega within iJavaScript / Jupyter Notebook

Note that vega (through altair) is supported in iPython through Altair

If we wanted to make simple charts within a JavaScript environment, such as the iJavaScript kernel, then what we need to do are four main steps.

The snippet below handles this for you, so you can do something like this:

Screenshot

Pre-Requisites

(Note, if you would like to use vega-datasets - you may need to shim fetch, possibly through npm install node-fetch)

Example

(See the --attached notebook-- Notebook Here for a complete example)

One Time Setup

(just include in a cell within jupyter once)

Vega = require('vega');
VegaLite = require('vega-lite');
VegaLiteApi = require('vega-lite-api');

/**
 * create an instance of vega lite we want to render with
 **/
vl = VegaLiteApi.register(Vega, VegaLite, {
  config: {
    // vega-lite default configuration
    config: {
      view: {},
      mark: { tooltip: null }
    }
  },
  view: {
    renderer: 'svg'
  }
});

/**
 * Render a vega lite instance within an iJavaScript display
 * ex:
 * vl.svg($$, vl.markPoint()
 *  .data(df)
 *  .width(700)
 *  .encode(
 *    vl.x().average('precip'),
 *    vl.y().fieldN('city')
 *  ));
 * 
 * @see https://observablehq.com/@uwdata/introduction-to-vega-lite
 * 
 * for more on displays
 * https://github.com/n-riesco/ijavascript/issues/95
 * 
 * for more on what you can do with displays
 * @see http://n-riesco.github.io/ijavascript/doc/custom.ipynb.html
 */
vl.svg = async (display, vlInstance) => {
  const spec = vlInstance.toSpec();
  const view = new Vega.View(Vega.parse(VegaLite.compile(spec).spec));
  const svgText = await view.toSVG();
  display.svg(svgText);
};

Running

df = [
  {"city": "Seattle",  "month": "Apr", "precip": 2.68},
  {"city": "Seattle",  "month": "Aug", "precip": 0.87},
  {"city": "Seattle",  "month": "Dec", "precip": 5.31},
  {"city": "New York", "month": "Apr", "precip": 3.94},
  {"city": "New York", "month": "Aug", "precip": 4.13},
  {"city": "New York", "month": "Dec", "precip": 3.58},
  {"city": "Chicago",  "month": "Apr", "precip": 3.62},
  {"city": "Chicago",  "month": "Aug", "precip": 3.98},
  {"city": "Chicago",  "month": "Dec", "precip": 2.56},
];

vl.svg($$, vl.markBar()
  .data(df)
  .encode(
    vl.x().average('precip'),
    vl.y().fieldN('city')
  ));
@paulroth3d
Copy link
Author

ExampleVegaChart

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment