A declarative visualization grammar for creating interactive data visualizations through JSON specifications.
—
Vega's scale and projection system provides data encoding through scales that map data values to visual properties, color schemes for categorical and continuous data, and geographic projections for cartographic visualizations.
Core scale creation and management for data encoding.
/**
* Create or access a scale function
* @param type - Scale type identifier
* @param scale - Optional scale configuration object
* @returns Scale function or scale registry entry
*/
function scale(type: string, scale?: ScaleConfig): ScaleFunction | any;
/**
* Access color scheme by name
* @param name - Color scheme name
* @param scheme - Optional scheme definition to register
* @returns Color scheme array or registration result
*/
function scheme(name: string, scheme?: ColorScheme): string[] | any;
interface ScaleConfig {
/** Scale domain (input range) */
domain?: any[];
/** Scale range (output range) */
range?: any[];
/** Scale type-specific parameters */
[key: string]: any;
}
interface ScaleFunction {
/** Map domain value to range value */
(value: any): any;
/** Get or set the scale domain */
domain(): any[];
domain(domain: any[]): ScaleFunction;
/** Get or set the scale range */
range(): any[];
range(range: any[]): ScaleFunction;
/** Create inverted scale function */
invert?(value: any): any;
/** Get scale bandwidth (for band scales) */
bandwidth?(): number;
/** Get scale step (for band scales) */
step?(): number;
/** Copy the scale */
copy(): ScaleFunction;
}
type ColorScheme = string[] | { [key: string]: string[] };Built-in scale types for different data mappings.
/** Linear scale for continuous numeric data */
type LinearScale = ScaleFunction & {
/** Get scale ticks */
ticks(count?: number): number[];
/** Get tick format function */
tickFormat(count?: number, specifier?: string): (value: number) => string;
/** Set interpolator function */
interpolate(interpolator: (a: any, b: any) => (t: number) => any): LinearScale;
/** Set clamping behavior */
clamp(clamp: boolean): LinearScale;
clamp(): boolean;
/** Set nice domain boundaries */
nice(count?: number): LinearScale;
};
/** Log scale for exponential data */
type LogScale = ScaleFunction & {
/** Set logarithm base */
base(base: number): LogScale;
base(): number;
/** Get scale ticks */
ticks(count?: number): number[];
/** Get tick format function */
tickFormat(count?: number, specifier?: string): (value: number) => string;
/** Set clamping behavior */
clamp(clamp: boolean): LogScale;
clamp(): boolean;
/** Set nice domain boundaries */
nice(): LogScale;
};
/** Power scale with configurable exponent */
type PowScale = ScaleFunction & {
/** Set power exponent */
exponent(exponent: number): PowScale;
exponent(): number;
/** Get scale ticks */
ticks(count?: number): number[];
/** Get tick format function */
tickFormat(count?: number, specifier?: string): (value: number) => string;
/** Set clamping behavior */
clamp(clamp: boolean): PowScale;
clamp(): boolean;
/** Set nice domain boundaries */
nice(count?: number): PowScale;
};
/** Square root scale (power scale with exponent 0.5) */
type SqrtScale = PowScale;
/** Symmetric log scale for data including zero */
type SymlogScale = ScaleFunction & {
/** Set linear threshold around zero */
constant(constant: number): SymlogScale;
constant(): number;
/** Get scale ticks */
ticks(count?: number): number[];
/** Get tick format function */
tickFormat(count?: number, specifier?: string): (value: number) => string;
/** Set clamping behavior */
clamp(clamp: boolean): SymlogScale;
clamp(): boolean;
/** Set nice domain boundaries */
nice(): SymlogScale;
};
/** Identity scale (passthrough) */
type IdentityScale = ScaleFunction;
/** Time scale for temporal data */
type TimeScale = ScaleFunction & {
/** Get scale ticks */
ticks(interval?: any): Date[];
/** Get tick format function */
tickFormat(count?: number, specifier?: string): (value: Date) => string;
/** Set clamping behavior */
clamp(clamp: boolean): TimeScale;
clamp(): boolean;
/** Set nice domain boundaries */
nice(interval?: any): TimeScale;
};
/** UTC time scale */
type UTCScale = TimeScale;
/** Sequential scale for continuous color mapping */
type SequentialScale = ScaleFunction & {
/** Set interpolator function */
interpolator(interpolator: (t: number) => any): SequentialScale;
interpolator(): (t: number) => any;
/** Set clamping behavior */
clamp(clamp: boolean): SequentialScale;
clamp(): boolean;
};
/** Diverging scale for data with meaningful center */
type DivergingScale = ScaleFunction & {
/** Set interpolator function */
interpolator(interpolator: (t: number) => any): DivergingScale;
interpolator(): (t: number) => any;
/** Set clamping behavior */
clamp(clamp: boolean): DivergingScale;
clamp(): boolean;
};
/** Quantile scale for statistical distributions */
type QuantileScale = ScaleFunction & {
/** Get quantiles array */
quantiles(): number[];
};
/** Quantize scale for uniform binning */
type QuantizeScale = ScaleFunction & {
/** Get thresholds array */
thresholds(): number[];
/** Set nice domain boundaries */
nice(count?: number): QuantizeScale;
};
/** Threshold scale for custom breakpoints */
type ThresholdScale = ScaleFunction & {
/** Set threshold values */
thresholds(thresholds: number[]): ThresholdScale;
thresholds(): number[];
};
/** Ordinal scale for categorical data */
type OrdinalScale = ScaleFunction & {
/** Get unknown value handler */
unknown(): any;
unknown(value: any): OrdinalScale;
};
/** Band scale for bar charts and similar */
type BandScale = ScaleFunction & {
/** Get bandwidth of each band */
bandwidth(): number;
/** Get step between band starts */
step(): number;
/** Set padding between bands */
padding(padding: number): BandScale;
padding(): number;
/** Set inner padding between bands */
paddingInner(padding: number): BandScale;
paddingInner(): number;
/** Set outer padding at scale edges */
paddingOuter(padding: number): BandScale;
paddingOuter(): number;
/** Set alignment of bands within range */
align(align: number): BandScale;
align(): number;
/** Round band positions to integers */
round(round: boolean): BandScale;
round(): boolean;
};
/** Point scale for scatterplots */
type PointScale = ScaleFunction & {
/** Get step between points */
step(): number;
/** Set padding at scale edges */
padding(padding: number): PointScale;
padding(): number;
/** Set alignment of points within range */
align(align: number): PointScale;
align(): number;
/** Round point positions to integers */
round(round: boolean): PointScale;
round(): boolean;
};Value interpolation for continuous scales.
/**
* Create interpolation function for continuous scales
* @param type - Interpolation type
* @param options - Interpolation options
* @returns Interpolation function
*/
function interpolate(type: string, options?: InterpolationOptions): (a: any, b: any) => (t: number) => any;
/**
* Color interpolation for color scales
* @param colors - Array of color values
* @param type - Interpolation type ('rgb', 'hsl', 'lab', etc.)
* @param options - Interpolation options
* @returns Color interpolation function
*/
function interpolateColors(colors: any[], type?: string, options?: InterpolationOptions): (t: number) => string;
/**
* Range interpolation for scale ranges
* @param range - Range values to interpolate
* @returns Range interpolation function
*/
function interpolateRange(range: any[]): (t: number) => any;
/**
* Create quantized interpolator
* @param interpolator - Base interpolation function
* @param count - Number of discrete steps
* @returns Quantized interpolation function
*/
function quantizeInterpolator(interpolator: (t: number) => any, count: number): (t: number) => any;
interface InterpolationOptions {
/** Color space for color interpolation */
colorSpace?: 'rgb' | 'hsl' | 'hcl' | 'lab' | 'cubehelix';
/** Gamma correction for color interpolation */
gamma?: number;
/** Use shorter hue path for hue interpolation */
hue?: 'shorter' | 'longer' | 'increasing' | 'decreasing';
}Scale manipulation utilities for panning and zooming.
/**
* Pan linear scale by specified offset
* @param scale - Linear scale to pan
* @param offset - Pan offset amount
* @returns New panned scale
*/
function panLinear(scale: LinearScale, offset: number): LinearScale;
/**
* Pan logarithmic scale by specified offset
* @param scale - Log scale to pan
* @param offset - Pan offset amount
* @returns New panned scale
*/
function panLog(scale: LogScale, offset: number): LogScale;
/**
* Pan power scale by specified offset
* @param scale - Power scale to pan
* @param offset - Pan offset amount
* @returns New panned scale
*/
function panPow(scale: PowScale, offset: number): PowScale;
/**
* Pan symmetric log scale by specified offset
* @param scale - Symlog scale to pan
* @param offset - Pan offset amount
* @returns New panned scale
*/
function panSymlog(scale: SymlogScale, offset: number): SymlogScale;
/**
* Zoom linear scale by specified factor
* @param scale - Linear scale to zoom
* @param anchor - Zoom anchor point
* @param factor - Zoom factor (>1 zooms in, <1 zooms out)
* @returns New zoomed scale
*/
function zoomLinear(scale: LinearScale, anchor: number, factor: number): LinearScale;
/**
* Zoom logarithmic scale by specified factor
* @param scale - Log scale to zoom
* @param anchor - Zoom anchor point
* @param factor - Zoom factor
* @returns New zoomed scale
*/
function zoomLog(scale: LogScale, anchor: number, factor: number): LogScale;
/**
* Zoom power scale by specified factor
* @param scale - Power scale to zoom
* @param anchor - Zoom anchor point
* @param factor - Zoom factor
* @returns New zoomed scale
*/
function zoomPow(scale: PowScale, anchor: number, factor: number): PowScale;
/**
* Zoom symmetric log scale by specified factor
* @param scale - Symlog scale to zoom
* @param anchor - Zoom anchor point
* @param factor - Zoom factor
* @returns New zoomed scale
*/
function zoomSymlog(scale: SymlogScale, anchor: number, factor: number): SymlogScale;Geographic coordinate system transformations.
/**
* Create or access a geographic projection
* @param type - Projection type identifier
* @param projection - Optional projection configuration
* @returns Projection function or projection registry entry
*/
function projection(type: string, projection?: ProjectionConfig): ProjectionFunction | any;
interface ProjectionConfig {
/** Projection center coordinates [longitude, latitude] */
center?: [number, number];
/** Projection rotation [yaw, pitch, roll] */
rotate?: [number, number, number?];
/** Projection scale factor */
scale?: number;
/** Projection translation offset [x, y] */
translate?: [number, number];
/** Clipping extent [[x0, y0], [x1, y1]] */
clipExtent?: [[number, number], [number, number]];
/** Clipping angle in degrees */
clipAngle?: number;
/** Precision for adaptive resampling */
precision?: number;
/** Projection-specific parameters */
[key: string]: any;
}
interface ProjectionFunction {
/** Project geographic coordinates to screen coordinates */
(coordinates: [number, number]): [number, number] | null;
/** Inverse projection from screen to geographic coordinates */
invert?(coordinates: [number, number]): [number, number] | null;
/** Get or set projection center */
center(): [number, number];
center(center: [number, number]): ProjectionFunction;
/** Get or set projection rotation */
rotate(): [number, number, number?];
rotate(angles: [number, number, number?]): ProjectionFunction;
/** Get or set projection scale */
scale(): number;
scale(scale: number): ProjectionFunction;
/** Get or set projection translation */
translate(): [number, number];
translate(translate: [number, number]): ProjectionFunction;
/** Get or set clipping extent */
clipExtent(): [[number, number], [number, number]] | null;
clipExtent(extent: [[number, number], [number, number]] | null): ProjectionFunction;
/** Get or set clipping angle */
clipAngle(): number | null;
clipAngle(angle: number | null): ProjectionFunction;
/** Get or set precision */
precision(): number;
precision(precision: number): ProjectionFunction;
/** Fit projection to geographic bounds */
fitExtent?(extent: [[number, number], [number, number]], object: any): ProjectionFunction;
/** Fit projection to geographic size */
fitSize?(size: [number, number], object: any): ProjectionFunction;
/** Copy the projection */
copy(): ProjectionFunction;
}Predefined color schemes for data visualization.
/** Categorical color schemes */
interface CategoricalSchemes {
/** 10-color categorical palette */
category10: string[];
/** 20-color categorical palette */
category20: string[];
/** 20b-color categorical palette */
category20b: string[];
/** 20c-color categorical palette */
category20c: string[];
/** Accent color scheme */
accent: string[];
/** Dark2 color scheme */
dark2: string[];
/** Paired color scheme */
paired: string[];
/** Pastel1 color scheme */
pastel1: string[];
/** Pastel2 color scheme */
pastel2: string[];
/** Set1 color scheme */
set1: string[];
/** Set2 color scheme */
set2: string[];
/** Set3 color scheme */
set3: string[];
/** Tableau10 color scheme */
tableau10: string[];
/** Tableau20 color scheme */
tableau20: string[];
}
/** Sequential color schemes */
interface SequentialSchemes {
/** Blues sequential scheme */
blues: string[];
/** Greens sequential scheme */
greens: string[];
/** Oranges sequential scheme */
oranges: string[];
/** Purples sequential scheme */
purples: string[];
/** Reds sequential scheme */
reds: string[];
/** Greys sequential scheme */
greys: string[];
/** Turbo perceptually uniform scheme */
turbo: string[];
/** Viridis perceptually uniform scheme */
viridis: string[];
/** Plasma perceptually uniform scheme */
plasma: string[];
/** Inferno perceptually uniform scheme */
inferno: string[];
/** Magma perceptually uniform scheme */
magma: string[];
/** Cividis colorblind-friendly scheme */
cividis: string[];
}
/** Diverging color schemes */
interface DivergingSchemes {
/** Blue-Red diverging scheme */
blueorange: string[];
/** Blue-White-Red diverging scheme */
bluewhitered: string[];
/** Brown-Blue-Green diverging scheme */
brownbluegreen: string[];
/** Purple-Green diverging scheme */
purplegreen: string[];
/** Purple-Orange diverging scheme */
purpleorange: string[];
/** Red-Blue diverging scheme */
redblue: string[];
/** Red-Grey diverging scheme */
redgrey: string[];
/** Red-Yellow-Blue diverging scheme */
redyellowblue: string[];
/** Red-Yellow-Green diverging scheme */
redyellowgreen: string[];
/** Spectral diverging scheme */
spectral: string[];
}import { scale } from "vega";
// Create linear scale
const xScale = scale('linear')
.domain([0, 100])
.range([0, 400]);
console.log(xScale(50)); // 200
// Create ordinal scale
const colorScale = scale('ordinal')
.domain(['A', 'B', 'C'])
.range(['red', 'green', 'blue']);
console.log(colorScale('B')); // 'green'import { scale } from "vega";
const timeScale = scale('time')
.domain([new Date('2023-01-01'), new Date('2023-12-31')])
.range([0, 500]);
// Map date to pixel position
const position = timeScale(new Date('2023-06-15'));
// Get nice tick values
const ticks = timeScale.ticks(5);
const tickFormat = timeScale.tickFormat(5, '%b');import { scale } from "vega";
const xScale = scale('band')
.domain(['Q1', 'Q2', 'Q3', 'Q4'])
.range([0, 400])
.padding(0.1);
// Get bar positions and widths
const barWidth = xScale.bandwidth();
const q2Position = xScale('Q2');
console.log(`Q2 bar at ${q2Position}, width ${barWidth}`);import { scheme, scale } from "vega";
// Use built-in color scheme
const colors = scheme('category10');
const colorScale = scale('ordinal')
.domain(['A', 'B', 'C'])
.range(colors);
// Sequential color scale
const seqColors = scheme('blues');
const heatmapScale = scale('sequential')
.domain([0, 100])
.range(seqColors);import { scale, interpolate, interpolateColors } from "vega";
// Custom color interpolation
const customColors = interpolateColors(['#ff0000', '#00ff00', '#0000ff'], 'lab');
const colorScale = scale('linear')
.domain([0, 100])
.range([0, 1])
.interpolate(() => customColors);
console.log(colorScale(50)); // Interpolated colorimport { projection } from "vega";
// Create Mercator projection
const proj = projection('mercator')
.scale(1000)
.center([0, 0])
.translate([400, 300]);
// Project coordinates
const [x, y] = proj([-74, 40.7]); // NYC coordinates
console.log(`NYC at screen coordinates: ${x}, ${y}`);
// Inverse projection
const [lng, lat] = proj.invert([x, y]);
console.log(`Back to geo coordinates: ${lng}, ${lat}`);import { scale, panLinear, zoomLinear } from "vega";
const baseScale = scale('linear')
.domain([0, 100])
.range([0, 500]);
// Pan the scale
const pannedScale = panLinear(baseScale, 50);
console.log(pannedScale.domain()); // [50, 150]
// Zoom the scale
const zoomedScale = zoomLinear(baseScale, 50, 2);
console.log(zoomedScale.domain()); // [25, 75]import { scale } from "vega";
const data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const quantileScale = scale('quantile')
.domain(data)
.range(['low', 'medium', 'high']);
console.log(quantileScale(3)); // 'low'
console.log(quantileScale(7)); // 'medium'
console.log(quantileScale(9)); // 'high'
// Get quantile boundaries
const quantiles = quantileScale.quantiles();
console.log(quantiles); // [3.25, 6.75]import { scale } from "vega";
const thresholdScale = scale('threshold')
.domain([0, 50, 100])
.range(['low', 'medium', 'high', 'very high']);
console.log(thresholdScale(-10)); // 'low'
console.log(thresholdScale(25)); // 'low'
console.log(thresholdScale(75)); // 'medium'
console.log(thresholdScale(150)); // 'very high'import { projection } from "vega";
// Albers projection for US maps
const usProjection = projection('albers')
.rotate([96, 0])
.center([-0.6, 38.7])
.parallels([29.5, 45.5])
.scale(1000)
.translate([400, 250]);
// Fit projection to bounding box
const bounds = {
type: "FeatureCollection",
features: [/* GeoJSON features */]
};
usProjection.fitSize([800, 500], bounds);Install with Tessl CLI
npx tessl i tessl/npm-vega