Headless Mode - smclements/vega GitHub Wiki

WikiDocumentationHeadless Mode

Vega can be run server-side using node.js to render visualizations outside the browser. When running in "headless" mode, Vega can render specifications directly to PNG (using node-canvas) or SVG.

Command Line Tools

Vega includes two command line tools for converting Vega JSON specifications to rendered PNG or SVG:

  • vg2png: vg2png [-b basedir] vega_json_file [output_png_file]
  • vg2svg: vg2svg [-b basedir] [-h] vega_json_file [output_svg_file]

If no output file is given, the resulting PNG or SVG data will be written to standard output, and so can be piped into other applications. The programs also accept the following (optional) parameters:

  • -b, --base - [String] A base directory to use for data and image loading. For web retrieval, use -b http://host/data/. For files, use -b file:///dir/data/ (absolute paths) or -b data/ (relative paths).
  • -h, --header - [Flag] Includes XML header and DOCTYPE in SVG output (vg2svg only).

Within the Vega project directories, you can use ./bin/vg2png or ./bin/vg2svg. If you import Vega using npm, the commands are accessible either locally (./node_modules/bin/vg2png) or globally (vg2png) depending on how you install the Vega package.

Examples

In the top-level Vega directory, you can run the following from the command line.

Render the bar chart example to a PNG file:

bin/vg2png examples/spec/bar.json bar.png

Render the bar chart example to an SVG file, including XML headers:

bin/vg2svg -h examples/spec/bar.json bar.svg

Render the choropleth example to a PNG file. A base directory is specified for loading data files:

bin/vg2png -b examples/ examples/spec/bar.json bar.svg

Render the arc example to SVG and pipe through svg2pdf (requires svg2pdf):

bin/vg2svg examples/spec/arc.json | svg2pdf > arc.pdf

Using Vega in node.js Projects

To include Vega in a node project, first install it from the command line using npm (npm install vega) or by including "vega" among the installed dependencies in your package.json file. In your node.js JavaScript code, import Vega using require('vega').

Headless Rendering

To render visualizations within node.js, call vg.parse.spec but do not specify an el when invoking the chart constructor. The view component will have two additional API methods: canvas to get the resulting node-canvas instance, or svg to get the resulting SVG text as appropriate.

For example, the following code will render to a canvas and return it for subsequent processing. For more about the returned canvas object, see the the node-canvas project.

vg.parse.spec(spec, function(chart) {
  var view = chart({ renderer: "canvas" })
    .update();

  var canvas = view.canvas();
  // do something with the node-canvas instance...
}