or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

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

0

# Vega

1

2

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.

3

4

## Package Information

5

6

- **Package Name**: vega

7

- **Package Type**: npm

8

- **Language**: TypeScript/JavaScript

9

- **Installation**: `npm install vega`

10

11

## Core Imports

12

13

```typescript

14

import * as vega from "vega";

15

```

16

17

For specific imports:

18

19

```typescript

20

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

21

```

22

23

CommonJS:

24

25

```javascript

26

const vega = require("vega");

27

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

28

```

29

30

## Basic Usage

31

32

```typescript

33

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

34

35

// Basic Vega specification

36

const spec = {

37

"$schema": "https://vega.github.io/schema/vega/v5.json",

38

"width": 400,

39

"height": 200,

40

"data": [

41

{

42

"name": "table",

43

"values": [

44

{"category": "A", "amount": 28},

45

{"category": "B", "amount": 55},

46

{"category": "C", "amount": 43}

47

]

48

}

49

],

50

"scales": [

51

{

52

"name": "xscale",

53

"type": "band",

54

"domain": {"data": "table", "field": "category"},

55

"range": "width",

56

"padding": 0.1

57

},

58

{

59

"name": "yscale",

60

"type": "linear",

61

"domain": {"data": "table", "field": "amount"},

62

"range": "height"

63

}

64

],

65

"marks": [

66

{

67

"type": "rect",

68

"from": {"data": "table"},

69

"encode": {

70

"enter": {

71

"x": {"scale": "xscale", "field": "category"},

72

"width": {"scale": "xscale", "band": 1},

73

"y": {"scale": "yscale", "field": "amount"},

74

"y2": {"scale": "yscale", "value": 0},

75

"fill": {"value": "steelblue"}

76

}

77

}

78

}

79

]

80

};

81

82

// Parse and render the visualization

83

const runtime = parse(spec);

84

const view = new View(runtime, {

85

loader: loader(),

86

renderer: 'canvas'

87

});

88

89

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

90

```

91

92

## Architecture

93

94

Vega is built around several key architectural components:

95

96

- **Specification Parser**: Converts JSON specifications into executable runtime objects

97

- **View System**: Manages visualization lifecycle, rendering, and interaction

98

- **Dataflow Engine**: Reactive data processing system with incremental updates

99

- **Scene Graph**: Hierarchical representation of visual elements for rendering

100

- **Transform Library**: Comprehensive data transformation pipeline

101

- **Scale System**: Data encoding and visual mapping utilities

102

- **Rendering Backends**: Multiple output formats (Canvas, SVG, hybrid rendering)

103

- **Expression Language**: Custom expression system for dynamic specifications

104

- **Event System**: Interaction and event handling framework

105

106

## Capabilities

107

108

### Specification Parsing

109

110

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

111

112

```typescript { .api }

113

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

114

115

interface Spec {

116

$schema?: string;

117

config?: Config;

118

description?: string;

119

width?: number | SignalRef;

120

height?: number | SignalRef;

121

padding?: Padding | SignalRef;

122

autosize?: AutoSize | SignalRef;

123

background?: Color | SignalRef;

124

data?: Data[];

125

scales?: Scale[];

126

marks?: Mark[];

127

signals?: Signal[];

128

// ... other specification properties

129

}

130

131

interface Runtime {

132

definition: any;

133

operators: Operator[];

134

streams: EventStream[];

135

}

136

```

137

138

[Specification Parsing](./parsing.md)

139

140

### View Management

141

142

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

143

144

```typescript { .api }

145

class View {

146

constructor(runtime: Runtime, options?: ViewOptions);

147

148

// Configuration

149

initialize(container?: Element | string, bindContainer?: Element | string): this;

150

finalize(): this;

151

152

// Rendering

153

run(encode?: string): this;

154

runAsync(): Promise<View>;

155

resize(): this;

156

157

// Data access

158

data(name: string): any[];

159

data(name: string, tuples: any): this;

160

161

// Signal access

162

signal(name: string): SignalValue;

163

signal(name: string, value: SignalValue): this;

164

}

165

166

interface ViewOptions {

167

background?: Color;

168

bind?: Element | string;

169

container?: Element | string;

170

hover?: boolean;

171

loader?: Loader;

172

logger?: LoggerInterface;

173

logLevel?: number;

174

renderer?: Renderers;

175

tooltip?: TooltipHandler;

176

locale?: LocaleFormatters;

177

}

178

```

179

180

[View Management](./view.md)

181

182

### Data Loading and Processing

183

184

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

185

186

```typescript { .api }

187

function loader(options?: LoaderOptions): Loader;

188

function read(data: string, schema: Format, dateParse?: (dateString: string) => Date): object[];

189

function inferType(values: readonly any[], field?: string): TypeInference;

190

function inferTypes(values: readonly any[], fields: readonly string[]): { [field: string]: TypeInference };

191

192

interface Loader {

193

load: (uri: string, options?: LoaderOptionsWithContext) => Promise<string>;

194

sanitize: (uri: string, options: LoaderOptionsWithContext) => Promise<{ href: string }>;

195

http: (uri: string, options: Partial<RequestInit>) => Promise<string>;

196

file: (filename: string) => Promise<string>;

197

}

198

```

199

200

[Data Loading](./data-loading.md)

201

202

### Reactive Dataflow System

203

204

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

205

206

```typescript { .api }

207

class Dataflow {

208

constructor();

209

add(operator: Operator): Dataflow;

210

connect(sourceOp: Operator, targetOp: Operator): Dataflow;

211

run(): Dataflow;

212

runAsync(): Promise<Dataflow>;

213

}

214

215

class Pulse {

216

constructor(dataflow: Dataflow, stamp?: number);

217

add: any[];

218

rem: any[];

219

mod: any[];

220

source: any[];

221

}

222

223

function changeset(): Changeset;

224

function ingest(datum: any): any;

225

function transforms: { [name: string]: Transform };

226

```

227

228

[Dataflow System](./dataflow.md)

229

230

### Scene Graph and Rendering

231

232

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

233

234

```typescript { .api }

235

class Scenegraph {

236

constructor(root?: GroupItem);

237

root: GroupItem;

238

toJSON(indent?: number): string;

239

}

240

241

class CanvasRenderer extends Renderer {

242

constructor(loader?: Loader);

243

canvas(): HTMLCanvasElement;

244

context(): CanvasRenderingContext2D;

245

}

246

247

class SVGRenderer extends Renderer {

248

constructor(loader?: Loader);

249

svg(): SVGSVGElement;

250

}

251

252

interface Item<T = any> {

253

datum: T;

254

mark: RuntimeMark;

255

}

256

```

257

258

[Scene Graph & Rendering](./scenegraph.md)

259

260

### Scales and Projections

261

262

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

263

264

```typescript { .api }

265

function scale(type: string, scale?: any): any;

266

function projection(type: string, projection: any): any;

267

function scheme(name: string, scheme?: any): any;

268

function interpolate(type: string, options?: any): any;

269

function interpolateColors(colors: any[], type?: string, options?: any): any;

270

```

271

272

[Scales & Projections](./scales.md)

273

274

### Statistical Functions

275

276

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

277

278

```typescript { .api }

279

// Distribution functions

280

function bin(options: BinOptions): (values: number[]) => Bin[];

281

function quantiles(values: number[], p: number[]): number[];

282

function quartiles(values: number[]): [number, number, number];

283

284

// Regression analysis

285

function regressionLinear(data: [number, number][]): RegressionResult;

286

function regressionLoess(data: [number, number][], options?: LoessOptions): RegressionResult;

287

288

// Random sampling

289

function randomNormal(mu?: number, sigma?: number): () => number;

290

function randomUniform(min?: number, max?: number): () => number;

291

```

292

293

[Statistical Functions](./statistics.md)

294

295

### Time Operations

296

297

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

298

299

```typescript { .api }

300

function timeInterval(unit: TimeUnit): TimeInterval;

301

function timeBin(options: TimeBinOptions): (date: Date) => Date;

302

function timeFloor(unit: TimeUnit): (date: Date) => Date;

303

function timeSequence(start: Date, stop: Date, step: TimeInterval): Date[];

304

305

// Time constants

306

const YEAR: string;

307

const MONTH: string;

308

const DAY: string;

309

const HOUR: string;

310

const MINUTE: string;

311

const SECOND: string;

312

```

313

314

[Time Operations](./time.md)

315

316

### Expression System

317

318

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

319

320

```typescript { .api }

321

function expressionFunction(name: string, fn?: any, visitor?: any): any;

322

function parseExpression(expression: string, options?: ParseOptions): ExpressionNode;

323

function codegenExpression(ast: ExpressionNode): Function;

324

```

325

326

[Expression System](./expressions.md)

327

328

### Event Handling

329

330

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

331

332

```typescript { .api }

333

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

334

335

class View {

336

addEventListener(type: string, handler: EventListenerHandler): this;

337

removeEventListener(type: string, handler: EventListenerHandler): this;

338

addSignalListener(name: string, handler: SignalListenerHandler): this;

339

removeSignalListener(name: string, handler: SignalListenerHandler): this;

340

}

341

342

type EventListenerHandler = (event: ScenegraphEvent, item?: Item | null) => void;

343

type SignalListenerHandler = (name: string, value: SignalValue) => void;

344

```

345

346

[Event Handling](./events.md)

347

348

### Utility Functions

349

350

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

351

352

```typescript { .api }

353

// Type checking

354

function isArray(value: any): boolean;

355

function isString(value: any): boolean;

356

function isNumber(value: any): boolean;

357

function isObject(value: any): boolean;

358

359

// Data manipulation

360

function extend(target: any, ...sources: any[]): any;

361

function merge(target: any, source: any): any;

362

function field(name: string): (datum: any) => any;

363

364

// Mathematical operations

365

function extent(values: any[]): [any, any];

366

function clampRange(range: [number, number], min: number, max: number): [number, number];

367

```

368

369

[Utility Functions](./utilities.md)

370

371

## Common Patterns

372

373

### Creating Visualizations

374

375

```typescript

376

// 1. Define specification

377

const spec = { /* Vega JSON specification */ };

378

379

// 2. Parse specification

380

const runtime = parse(spec);

381

382

// 3. Create and initialize view

383

const view = new View(runtime, { renderer: 'canvas' });

384

view.initialize('#visualization');

385

386

// 4. Run the visualization

387

view.run();

388

```

389

390

### Data Updates

391

392

```typescript

393

// Add new data

394

view.data('myDataset', newData).run();

395

396

// Incremental updates

397

const changeset = vega.changeset()

398

.insert([{ x: 1, y: 2 }])

399

.remove([{ x: 0, y: 1 }]);

400

401

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

402

```

403

404

### Interactive Visualizations

405

406

```typescript

407

// Signal updates

408

view.signal('selectedCategory', 'A').run();

409

410

// Event listeners

411

view.addEventListener('click', (event, item) => {

412

console.log('Clicked item:', item);

413

});

414

```

415

416

## Version Information

417

418

```typescript { .api }

419

const version: string;

420

```

421

422

Export of the current Vega library version.