Vega-Lite API

6.0.0 · active · verified Tue Apr 21

The Vega-Lite API (version 6.0.0) provides a JavaScript fluent API for programmatically constructing Vega-Lite JSON specifications. It serves as a high-level grammar for visual analysis, enabling developers to define interactive visualizations in a more structured and code-centric manner than direct JSON manipulation. The package tracks the major version of Vega-Lite, ensuring compatibility with the underlying visualization grammar; v6.x of this API is compatible with Vega-Lite v6.x. It differentiates itself by offering a declarative chaining syntax that simplifies complex specification creation, particularly beneficial in environments like Observable notebooks or browser-based applications where dynamic chart generation is common. The API is actively maintained with releases tied to Vega-Lite updates, providing a stable and evolving tool for data visualization, primarily aimed at simplifying the creation of complex charts.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create a simple bar chart using the Vega-Lite API. It includes the necessary imports and the critical `vl.register` step for browser or bundled environments, then builds a chart specification and outputs its JSON representation.

import { vl } from 'vega-lite-api';
import vega from 'vega';
import vegaLite from 'vega-lite';

// In a browser environment, you would typically load vega, vega-lite, and vega-tooltip via CDN.
// For Node.js or bundlers, you'd import them.
// For this example, we mock the registration that happens in a browser.

const options = {
  config: {
    // vega-lite default configuration
  },
  init: (view) => {
    // Example: enable horizontal scrolling for large plots
    // if (view.container()) view.container().style["overflow-x"] = "auto";
  },
  view: {
    // view constructor options
    loader: vega.loader({
      baseURL: "https://cdn.jsdelivr.net/npm/vega-datasets@1/"
    }),
    renderer: "canvas"
  }
};

// Simulate browser registration for demonstration
const mockGlobalVega = vega;
const mockGlobalVegaLite = vegaLite;
if (typeof globalThis !== 'undefined') {
  globalThis.vega = mockGlobalVega;
  globalThis.vegaLite = mockGlobalVegaLite;
}

vl.register(mockGlobalVega, mockGlobalVegaLite, options);

const chartSpec = vl.markBar({ tooltip: true })
  .data([
    { a: "A", b: 28 },
    { a: "B", b: 55 },
    { a: "C", b: 43 },
    { a: "D", b: 91 },
    { a: "E", b: 81 }
  ])
  .encode(
    vl.x().fieldQ("b"),
    vl.y().fieldN("a"),
    vl.tooltip([vl.fieldQ("b"), vl.fieldN("a")])
  )
  .toJSON();

// In a real browser scenario, you would call .render().then(chart => document.body.appendChild(chart));
// For a Node.js context, you would typically work with the JSON specification.

console.log(JSON.stringify(chartSpec, null, 2));

view raw JSON →