or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

data-loading.mddataflow.mdevents.mdexpressions.mdindex.mdparsing.mdscales.mdscenegraph.mdstatistics.mdtime.mdutilities.mdview.md
tile.json

tessl/npm-vega

A declarative visualization grammar for creating interactive data visualizations through JSON specifications.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/vega@6.1.x

To install, run

npx @tessl/cli install tessl/npm-vega@6.1.0

index.mddocs/

Vega

Vega is a declarative visualization grammar that enables developers to create interactive data visualizations through JSON specifications. It provides a comprehensive framework for describing data visualizations that can be rendered using HTML5 Canvas or SVG, supporting complex interactive behaviors, data transformations, and a wide range of visualization types from basic charts to sophisticated multi-view dashboards.

Package Information

  • Package Name: vega
  • Package Type: npm
  • Language: TypeScript/JavaScript
  • Installation: npm install vega

Core Imports

import * as vega from "vega";

For specific imports:

import { View, parse, loader, transforms } from "vega";

CommonJS:

const vega = require("vega");
const { View, parse, loader } = require("vega");

Basic Usage

import { parse, View, loader } from "vega";

// Basic Vega specification
const spec = {
  "$schema": "https://vega.github.io/schema/vega/v5.json",
  "width": 400,
  "height": 200,
  "data": [
    {
      "name": "table",
      "values": [
        {"category": "A", "amount": 28},
        {"category": "B", "amount": 55},
        {"category": "C", "amount": 43}
      ]
    }
  ],
  "scales": [
    {
      "name": "xscale",
      "type": "band",
      "domain": {"data": "table", "field": "category"},
      "range": "width",
      "padding": 0.1
    },
    {
      "name": "yscale",
      "type": "linear",
      "domain": {"data": "table", "field": "amount"},
      "range": "height"
    }
  ],
  "marks": [
    {
      "type": "rect",
      "from": {"data": "table"},
      "encode": {
        "enter": {
          "x": {"scale": "xscale", "field": "category"},
          "width": {"scale": "xscale", "band": 1},
          "y": {"scale": "yscale", "field": "amount"},
          "y2": {"scale": "yscale", "value": 0},
          "fill": {"value": "steelblue"}
        }
      }
    }
  ]
};

// Parse and render the visualization
const runtime = parse(spec);
const view = new View(runtime, {
  loader: loader(),
  renderer: 'canvas'
});

view.initialize('#vis').run();

Architecture

Vega is built around several key architectural components:

  • Specification Parser: Converts JSON specifications into executable runtime objects
  • View System: Manages visualization lifecycle, rendering, and interaction
  • Dataflow Engine: Reactive data processing system with incremental updates
  • Scene Graph: Hierarchical representation of visual elements for rendering
  • Transform Library: Comprehensive data transformation pipeline
  • Scale System: Data encoding and visual mapping utilities
  • Rendering Backends: Multiple output formats (Canvas, SVG, hybrid rendering)
  • Expression Language: Custom expression system for dynamic specifications
  • Event System: Interaction and event handling framework

Capabilities

Specification Parsing

Core functionality for parsing Vega JSON specifications into executable runtime objects that can be rendered and interacted with.

function parse(spec: Spec, config?: Config, options?: { ast?: boolean }): Runtime;

interface Spec {
  $schema?: string;
  config?: Config;
  description?: string;
  width?: number | SignalRef;
  height?: number | SignalRef;
  padding?: Padding | SignalRef;
  autosize?: AutoSize | SignalRef;
  background?: Color | SignalRef;
  data?: Data[];
  scales?: Scale[];
  marks?: Mark[];
  signals?: Signal[];
  // ... other specification properties
}

interface Runtime {
  definition: any;
  operators: Operator[];
  streams: EventStream[];
}

Specification Parsing

View Management

Main visualization management system that handles rendering, data binding, interaction, and lifecycle management for Vega visualizations.

class View {
  constructor(runtime: Runtime, options?: ViewOptions);
  
  // Configuration
  initialize(container?: Element | string, bindContainer?: Element | string): this;
  finalize(): this;
  
  // Rendering
  run(encode?: string): this;
  runAsync(): Promise<View>;
  resize(): this;
  
  // Data access
  data(name: string): any[];
  data(name: string, tuples: any): this;
  
  // Signal access
  signal(name: string): SignalValue;
  signal(name: string, value: SignalValue): this;
}

interface ViewOptions {
  background?: Color;
  bind?: Element | string;
  container?: Element | string;
  hover?: boolean;
  loader?: Loader;
  logger?: LoggerInterface;
  logLevel?: number;
  renderer?: Renderers;
  tooltip?: TooltipHandler;
  locale?: LocaleFormatters;
}

View Management

Data Loading and Processing

Comprehensive data loading system with support for multiple formats, type inference, and network/file system access.

function loader(options?: LoaderOptions): Loader;
function read(data: string, schema: Format, dateParse?: (dateString: string) => Date): object[];
function inferType(values: readonly any[], field?: string): TypeInference;
function inferTypes(values: readonly any[], fields: readonly string[]): { [field: string]: TypeInference };

interface Loader {
  load: (uri: string, options?: LoaderOptionsWithContext) => Promise<string>;
  sanitize: (uri: string, options: LoaderOptionsWithContext) => Promise<{ href: string }>;
  http: (uri: string, options: Partial<RequestInit>) => Promise<string>;
  file: (filename: string) => Promise<string>;
}

Data Loading

Reactive Dataflow System

Powerful reactive data processing engine with incremental updates, transforms, and change tracking for efficient visualization updates.

class Dataflow {
  constructor();
  add(operator: Operator): Dataflow;
  connect(sourceOp: Operator, targetOp: Operator): Dataflow;
  run(): Dataflow;
  runAsync(): Promise<Dataflow>;
}

class Pulse {
  constructor(dataflow: Dataflow, stamp?: number);
  add: any[];
  rem: any[];
  mod: any[];
  source: any[];
}

function changeset(): Changeset;
function ingest(datum: any): any;
function transforms: { [name: string]: Transform };

Dataflow System

Scene Graph and Rendering

Multi-backend rendering system supporting Canvas, SVG, and hybrid rendering with comprehensive scene graph management and visual element handling.

class Scenegraph {
  constructor(root?: GroupItem);
  root: GroupItem;
  toJSON(indent?: number): string;
}

class CanvasRenderer extends Renderer {
  constructor(loader?: Loader);
  canvas(): HTMLCanvasElement;
  context(): CanvasRenderingContext2D;
}

class SVGRenderer extends Renderer {
  constructor(loader?: Loader);
  svg(): SVGSVGElement;
}

interface Item<T = any> {
  datum: T;
  mark: RuntimeMark;
}

Scene Graph & Rendering

Scales and Projections

Data encoding system with scales for mapping data values to visual properties and geographic projections for cartographic visualizations.

function scale(type: string, scale?: any): any;
function projection(type: string, projection: any): any;
function scheme(name: string, scheme?: any): any;
function interpolate(type: string, options?: any): any;
function interpolateColors(colors: any[], type?: string, options?: any): any;

Scales & Projections

Statistical Functions

Comprehensive statistical analysis library with distribution functions, regression analysis, binning, and random number generation.

// Distribution functions
function bin(options: BinOptions): (values: number[]) => Bin[];
function quantiles(values: number[], p: number[]): number[];
function quartiles(values: number[]): [number, number, number];

// Regression analysis
function regressionLinear(data: [number, number][]): RegressionResult;
function regressionLoess(data: [number, number][], options?: LoessOptions): RegressionResult;

// Random sampling
function randomNormal(mu?: number, sigma?: number): () => number;
function randomUniform(min?: number, max?: number): () => number;

Statistical Functions

Time Operations

Time-based data processing with interval calculations, time formatting, binning, and temporal scale operations.

function timeInterval(unit: TimeUnit): TimeInterval;
function timeBin(options: TimeBinOptions): (date: Date) => Date;
function timeFloor(unit: TimeUnit): (date: Date) => Date;
function timeSequence(start: Date, stop: Date, step: TimeInterval): Date[];

// Time constants
const YEAR: string;
const MONTH: string;
const DAY: string;
const HOUR: string;
const MINUTE: string;
const SECOND: string;

Time Operations

Expression System

Custom expression language for dynamic specifications with function registration, parsing, and code generation capabilities.

function expressionFunction(name: string, fn?: any, visitor?: any): any;
function parseExpression(expression: string, options?: ParseOptions): ExpressionNode;
function codegenExpression(ast: ExpressionNode): Function;

Expression System

Event Handling

Event system for interactive visualizations with event parsing, selection, and handler management.

function parseSelector(selector: string): EventSelector[];

class View {
  addEventListener(type: string, handler: EventListenerHandler): this;
  removeEventListener(type: string, handler: EventListenerHandler): this;
  addSignalListener(name: string, handler: SignalListenerHandler): this;
  removeSignalListener(name: string, handler: SignalListenerHandler): this;
}

type EventListenerHandler = (event: ScenegraphEvent, item?: Item | null) => void;
type SignalListenerHandler = (name: string, value: SignalValue) => void;

Event Handling

Utility Functions

Comprehensive utility library with type checking, data manipulation, mathematical operations, and general-purpose helper functions.

// Type checking
function isArray(value: any): boolean;
function isString(value: any): boolean;
function isNumber(value: any): boolean;
function isObject(value: any): boolean;

// Data manipulation
function extend(target: any, ...sources: any[]): any;
function merge(target: any, source: any): any;
function field(name: string): (datum: any) => any;

// Mathematical operations
function extent(values: any[]): [any, any];
function clampRange(range: [number, number], min: number, max: number): [number, number];

Utility Functions

Common Patterns

Creating Visualizations

// 1. Define specification
const spec = { /* Vega JSON specification */ };

// 2. Parse specification
const runtime = parse(spec);

// 3. Create and initialize view
const view = new View(runtime, { renderer: 'canvas' });
view.initialize('#visualization');

// 4. Run the visualization
view.run();

Data Updates

// Add new data
view.data('myDataset', newData).run();

// Incremental updates
const changeset = vega.changeset()
  .insert([{ x: 1, y: 2 }])
  .remove([{ x: 0, y: 1 }]);

view.change('myDataset', changeset).run();

Interactive Visualizations

// Signal updates
view.signal('selectedCategory', 'A').run();

// Event listeners
view.addEventListener('click', (event, item) => {
  console.log('Clicked item:', item);
});

Version Information

const version: string;

Export of the current Vega library version.