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:
- setup iJavaScript as a running kernel
- (within your notebook directory) npm install vega vega-lite vega-lite-api
(Note, if you would like to use vega-datasets - you may need to shim fetch, possibly through npm install node-fetch
)
(See the --attached notebook-- Notebook Here for a complete example)
(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);
};
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')
));