CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-antv--g2

Grammar of Graphics visualization library for JavaScript with declarative API for creating interactive data visualizations

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

G2

G2 is a comprehensive visualization grammar library for JavaScript that enables developers to create powerful data visualizations for dashboard building, data exploration, and storytelling. Built on the Grammar of Graphics principles, it provides a declarative API that allows users to specify chart options programmatically with progressive usage - from simple, concise declarations for quick visualizations to advanced configurations for complex scenarios.

Package Information

  • Package Name: @antv/g2
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install @antv/g2

Core Imports

import { Chart } from "@antv/g2";

For CommonJS:

const { Chart } = require("@antv/g2");

Advanced imports:

import { 
  Chart, 
  Runtime, 
  extend, 
  register,
  render,
  renderToMountedElement,
  type G2Spec,
  type ChartOptions 
} from "@antv/g2";

Basic Usage

import { Chart } from "@antv/g2";

// Create a simple bar chart
const chart = new Chart({
  container: "container",
  width: 640,
  height: 480,
});

chart
  .interval()
  .data([
    { genre: "Sports", sold: 275 },
    { genre: "Strategy", sold: 115 },
    { genre: "Action", sold: 120 },
    { genre: "Shooter", sold: 350 },
    { genre: "Other", sold: 150 },
  ])
  .encode("x", "genre")
  .encode("y", "sold");

chart.render();

Architecture

G2 is built around several key architectural components:

  • Grammar of Graphics Engine: Core visualization grammar implementing marks, scales, coordinates, and transforms
  • Runtime System: Chart rendering and lifecycle management with DOM integration
  • Component Libraries: Modular collections (corelib, plotlib, graphlib, geolib) for different visualization needs
  • Specification System: Declarative chart configuration using JSON-like specifications
  • Extension System: Plugin architecture for custom marks, transforms, interactions, and components
  • Multi-Renderer Support: Canvas, SVG, and WebGL rendering backends

Capabilities

Chart Creation and Runtime

Core chart creation functionality with the Chart class and runtime system for rendering visualizations to the DOM.

class Chart {
  constructor(options?: ChartOptions): Chart;
  render(): Promise<Chart>;
  destroy(): void;
}

interface ChartOptions {
  container?: string | HTMLElement;
  canvas?: any;
  width?: number;
  height?: number;
  depth?: number;
  autoFit?: boolean;
  renderer?: string;
  plugins?: any[];
  theme?: string | object;
}

Chart Creation and Runtime

Marks and Visual Elements

Comprehensive mark system for creating different types of visual elements including geometric shapes, statistical marks, and specialized visualizations.

// Basic marks
interval(): MarkNode; // Bar charts, histograms
line(): MarkNode;     // Line charts
point(): MarkNode;    // Scatter plots
text(): MarkNode;     // Text labels
area(): MarkNode;     // Area charts

// Statistical marks
boxplot(): MarkNode;  // Box plots
density(): MarkNode;  // Density plots
heatmap(): MarkNode;  // Heatmaps

// Graph marks
sankey(): MarkNode;   // Sankey diagrams
tree(): MarkNode;     // Tree diagrams
forceGraph(): MarkNode; // Force-directed graphs

Marks and Visual Elements

Data Processing and Transforms

Data transformation system for preprocessing, aggregating, and reshaping data before visualization.

// Statistical transforms
transform(name: "stackY", options?: StackYOptions): MarkNode;
transform(name: "binX", options?: BinXOptions): MarkNode;
transform(name: "dodgeX", options?: DodgeXOptions): MarkNode;

// Grouping and selection
transform(name: "groupX" | "groupY" | "groupColor", options?: GroupOptions): MarkNode;
transform(name: "select" | "selectX" | "selectY", options?: SelectOptions): MarkNode;

// Data operations
data(data: any[]): MarkNode;
data(data: { type: string; value: any[] | string; [key: string]: any }): MarkNode;

Data Processing and Transforms

Visual Encoding and Scales

Visual encoding system that maps data values to visual properties like position, color, and size through various scale types.

// Encoding methods
encode(channel: string, field: string | number | EncodeFunction): MarkNode;

// Scale specifications
scale(channel: string, options: ScaleOptions): MarkNode;

interface ScaleOptions {
  type?: "linear" | "ordinal" | "band" | "point" | "time" | "log" | "pow" | "sqrt";
  domain?: any[];
  range?: any[];
  nice?: boolean;
  zero?: boolean;
}

Visual Encoding and Scales

Coordinate Systems

Coordinate transformation system supporting various projections including cartesian, polar, and specialized coordinate systems.

// Coordinate system methods
coordinate(type: "cartesian", options?: CartesianOptions): MarkNode;
coordinate(type: "polar", options?: PolarOptions): MarkNode;
coordinate(type: "theta", options?: ThetaOptions): MarkNode;
coordinate(type: "parallel", options?: ParallelOptions): MarkNode;

interface CoordinateOptions {
  transform?: Array<{ type: string; [key: string]: any }>;
}

Coordinate Systems

Components and Legends

Chart component system including axes, legends, titles, and interactive components for enhancing visualizations.

// Axis components
component(type: "axisX" | "axisY", options?: AxisOptions): Chart;

// Legend components  
component(type: "legendCategory" | "legendContinuous", options?: LegendOptions): Chart;

// Interactive components
component(type: "sliderX" | "sliderY", options?: SliderOptions): Chart;
component(type: "scrollbarX" | "scrollbarY", options?: ScrollbarOptions): Chart;

interface AxisOptions {
  title?: string | boolean;
  grid?: boolean;
  tick?: boolean;
  label?: boolean;
}

Components and Legends

Interactions and Events

Interactive behavior system providing hover effects, selection, brushing, and custom interaction patterns.

// Element interactions
interaction(type: "elementHighlight" | "elementSelect", options?: InteractionOptions): Chart;

// Brush interactions
interaction(type: "brushFilter" | "brushHighlight", options?: BrushOptions): Chart;

// Component interactions
interaction(type: "tooltip" | "legendFilter", options?: ComponentInteractionOptions): Chart;

interface InteractionOptions {
  by?: string;
  groupBy?: string;
  link?: boolean;
}

Interactions and Events

Compositions and Layouts

Layout system for creating complex multi-chart visualizations including faceting, layering, and dashboard-style layouts.

// Layout compositions
spaceLayer(): CompositionNode;
spaceFlex(): CompositionNode;
facetRect(): CompositionNode;
facetCircle(): CompositionNode;

// Specialized compositions
geoView(): CompositionNode;  // Geographic visualizations
timingKeyframe(): CompositionNode; // Animation timelines

Compositions and Layouts

Animation and Transitions

Animation system providing enter/exit transitions, morphing animations, and timeline-based keyframe animations.

// Animation methods
animate(options: AnimationOptions): MarkNode;

interface AnimationOptions {
  enter?: {
    type: "fadeIn" | "scaleInX" | "scaleInY" | "growInX" | "growInY";
    duration?: number;
    delay?: number;
  };
  update?: {
    type: "morphing";
    duration?: number;
  };
  exit?: {
    type: "fadeOut" | "scaleOutX" | "scaleOutY";
    duration?: number;
  };
}

Animation and Transitions

Themes and Styling

Theme system with built-in themes and customization options for colors, fonts, and visual styling.

// Built-in themes
import { Light, Dark, Academy, Classic, ClassicDark } from "@antv/g2";

// Theme application
const chart = new Chart({
  theme: Light, // or "light" as string
});

// Custom theme
interface ThemeOptions {
  colors?: string[];
  fontFamily?: string;
  fontSize?: number;
}

Themes and Styling

Extension and Customization

Extension system for registering custom marks, transforms, interactions, and components to extend G2's capabilities.

import { register, extend, Runtime } from "@antv/g2";

// Register custom components
register(name: string, component: any, library?: any): void;

// Create custom Chart class
const CustomChart = extend(Runtime, customLibrary);

// Library creation
function createLibrary() {
  return {
    "mark.customMark": CustomMarkComponent,
    "transform.customTransform": CustomTransformComponent,
  };
}

Extension and Customization

Types

Core Types

interface G2Spec {
  width?: number;
  height?: number;
  depth?: number;
  autoFit?: boolean;
}

interface MarkNode {
  data(data: any[]): MarkNode;
  encode(channel: string, field: string | EncodeFunction): MarkNode;
  transform(name: string, options?: any): MarkNode;
  coordinate(type: string, options?: any): MarkNode;
  scale(channel: string, options?: ScaleOptions): MarkNode;
  animate(options?: AnimationOptions): MarkNode;
  style(options?: StyleOptions): MarkNode;
}

interface CompositionNode {
  children(...children: (MarkNode | CompositionNode)[]): CompositionNode;
}

type EncodeFunction = (data: any, index: number, array: any[]) => any;

Library Types

interface Library {
  [key: string]: any;
}

// Library functions return complete component registries
function corelib(): Library;
function litelib(): Library;  
function stdlib(): Library;
function plotlib(): Library;
function graphlib(): Library;
function geolib(): Library;

Utility Functions

/**
 * Creates a selection object for DOM manipulation
 * @param selector - CSS selector or DOM element
 * @returns Selection object with query methods
 */
function select(selector: string | Element): Selection;

/**
 * Selection class for DOM element manipulation
 */
class Selection {
  /** Select all matching elements */
  selectAll(selector: string): Selection;
  /** Get/set attributes */
  attr(name: string): string;
  attr(name: string, value: string): Selection;
  /** Get/set styles */
  style(name: string): string;
  style(name: string, value: string): Selection;
  /** Get/set text content */
  text(): string;
  text(value: string): Selection;
  /** Add event listeners */
  on(event: string, handler: Function): Selection;
  /** Remove elements */
  remove(): Selection;
}

/**
 * Extracts data from chart elements
 * @param elements - Chart elements
 * @returns Extracted data array
 */
function dataOf(elements: any[]): any[];

/**
 * Extracts series data from chart elements
 * @param elements - Chart elements
 * @returns Series data array
 */
function seriesOf(elements: any[]): any[];

/**
 * Selects G2 chart elements for interaction
 * @param chart - Chart instance
 * @param selector - Element selector
 * @returns Selected elements
 */
function selectG2Elements(chart: Chart, selector: string): any[];

/**
 * Selects the plot area of a chart
 * @param chart - Chart instance
 * @returns Plot area element
 */
function selectPlotArea(chart: Chart): any;

Event System

/**
 * Chart event class for handling interactions
 */
class ChartEvent {
  /** Event type */
  type: string;
  /** Event target element */
  target: any;
  /** Associated data */
  data?: any;
  /** Mouse/touch coordinates */
  x?: number;
  y?: number;
  /** Native browser event */
  nativeEvent?: Event;
  /** Prevent default behavior */
  preventDefault(): void;
  /** Stop event propagation */
  stopPropagation(): void;
}

Runtime Context

/**
 * G2 rendering context interface
 */
interface G2Context {
  /** Canvas or SVG element */
  canvas: any;
  /** Rendering group */
  group: any;
  /** Theme configuration */
  theme: any;
  /** Library registry */
  library: Library;
  /** Event emitter */
  emitter: any;
}
Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/@antv/g2@5.4.x
Publish Source
CLI
Badge
tessl/npm-antv--g2 badge