D3 is a comprehensive JavaScript library for creating dynamic, interactive data visualizations in web browsers. It provides a low-level, flexible approach built on web standards (HTML, SVG, CSS) that offers unparalleled control over the final visual result. D3 binds arbitrary data to the Document Object Model (DOM), then applies data-driven transformations to create rich, interactive visualizations.
npm install d3ES Modules (recommended):
import * as d3 from "d3";
// Or import specific functions
import { select, scaleLinear, axisBottom } from "d3";CommonJS:
const d3 = require("d3");
// Or destructure specific functions
const { select, scaleLinear, axisBottom } = require("d3");Browser UMD:
<script src="https://cdn.jsdelivr.net/npm/d3@7"></script>
<!-- d3 is available as global variable -->import * as d3 from "d3";
// Create an SVG container
const svg = d3.select("body")
.append("svg")
.attr("width", 400)
.attr("height", 200);
// Sample data
const data = [10, 20, 30, 25, 15];
// Create scale functions
const xScale = d3.scaleBand()
.domain(d3.range(data.length))
.range([0, 400])
.padding(0.1);
const yScale = d3.scaleLinear()
.domain([0, d3.max(data)])
.range([200, 0]);
// Create bars
svg.selectAll("rect")
.data(data)
.join("rect")
.attr("x", (d, i) => xScale(i))
.attr("y", d => yScale(d))
.attr("width", xScale.bandwidth())
.attr("height", d => 200 - yScale(d))
.attr("fill", "steelblue");D3 is structured as a meta-package that re-exports functionality from 27 specialized modules, each handling specific aspects of data visualization:
Core functionality for selecting and manipulating DOM elements, binding data, and handling events.
// Selection functions
function select(selector: string): Selection<HTMLElement>;
function selectAll(selector: string): Selection<HTMLElement>;
// Selection methods (subset of key methods)
interface Selection<T> {
select(selector: string): Selection<HTMLElement>;
selectAll(selector: string): Selection<HTMLElement>;
attr(name: string, value?: any): Selection<T>;
style(name: string, value?: any): Selection<T>;
text(value?: string): Selection<T>;
data<D>(data: D[]): Selection<T>;
join(enter?: string): Selection<T>;
on(type: string, listener: Function): Selection<T>;
}DOM Selection and Manipulation
Encoding functions that map abstract data dimensions to visual representations, plus axis generators for creating reference marks.
// Linear scale
function scaleLinear(): LinearScale;
interface LinearScale {
(value: number): number;
domain(domain: number[]): LinearScale;
range(range: number[]): LinearScale;
invert(value: number): number;
}
// Axis generators
function axisBottom(scale: Scale): Axis;
function axisLeft(scale: Scale): Axis;
interface Axis {
(selection: Selection): void;
scale(scale: Scale): Axis;
ticks(count?: number): Axis;
tickFormat(format?: Function): Axis;
}Utilities for loading external data files and performing statistical operations, transformations, and aggregations.
// Data loading
function csv(url: string): Promise<any[]>;
function json(url: string): Promise<any>;
function tsv(url: string): Promise<any[]>;
// Array operations
function max(array: number[]): number;
function min(array: number[]): number;
function extent(array: number[]): [number, number];
function sum(array: number[]): number;
function mean(array: number[]): number;
function group(iterable: any[], ...keys: Function[]): Map;SVG path generators for creating lines, areas, arcs, and other geometric shapes with configurable properties.
// Line generator
function line(): Line;
interface Line {
(data: any[]): string;
x(accessor: Function): Line;
y(accessor: Function): Line;
curve(curve: Function): Line;
}
// Area generator
function area(): Area;
interface Area {
(data: any[]): string;
x(accessor: Function): Area;
y0(accessor: Function): Area;
y1(accessor: Function): Area;
}
// Arc generator
function arc(): Arc;
interface Arc {
(data: any): string;
innerRadius(radius: Function): Arc;
outerRadius(radius: Function): Arc;
startAngle(angle: Function): Arc;
endAngle(angle: Function): Arc;
}Color space conversion, manipulation, and interpolation functions for creating smooth transitions and color schemes.
// Color functions
function color(specifier: string): Color;
function rgb(r: number, g: number, b: number): Color;
function hsl(h: number, s: number, l: number): Color;
interface Color {
opacity: number;
brighter(k?: number): Color;
darker(k?: number): Color;
formatHex(): string;
formatRgb(): string;
}
// Interpolation
function interpolate(a: any, b: any): Function;
function interpolateNumber(a: number, b: number): Function;
function interpolateRgb(a: string, b: string): Function;Smooth animated transitions between states with customizable timing, easing, and attribute interpolation.
// Transition methods
interface Selection<T> {
transition(name?: string): Transition<T>;
interrupt(name?: string): Selection<T>;
}
interface Transition<T> {
attr(name: string, value: any): Transition<T>;
style(name: string, value: any): Transition<T>;
duration(milliseconds: number): Transition<T>;
delay(milliseconds: number): Transition<T>;
ease(easing: Function): Transition<T>;
}
// Easing functions
const easeLinear: Function;
const easeCubic: Function;
const easeElastic: Function;Algorithms for positioning elements in hierarchical, network, and specialized layout patterns.
// Hierarchy layout
function hierarchy(data: any): HierarchyNode;
interface HierarchyNode {
data: any;
parent: HierarchyNode | null;
children: HierarchyNode[] | null;
descendants(): HierarchyNode[];
ancestors(): HierarchyNode[];
sum(value: Function): HierarchyNode;
}
// Tree layout
function tree(): TreeLayout;
interface TreeLayout {
(root: HierarchyNode): HierarchyNode;
size(size: [number, number]): TreeLayout;
nodeSize(size: [number, number]): TreeLayout;
}
// Force simulation
function forceSimulation(nodes?: any[]): Simulation;
interface Simulation {
nodes(nodes: any[]): Simulation;
force(name: string, force: Function): Simulation;
alpha(alpha: number): Simulation;
restart(): Simulation;
stop(): Simulation;
}Mathematical functions for converting spherical coordinates to planar coordinates for mapping applications.
// Path generator
function geoPath(projection?: Function): GeoPath;
interface GeoPath {
(object: any): string;
projection(projection: Function): GeoPath;
area(object: any): number;
bounds(object: any): [[number, number], [number, number]];
}
// Projections
function geoMercator(): Projection;
function geoAlbers(): Projection;
interface Projection {
(coordinates: [number, number]): [number, number];
scale(scale: number): Projection;
translate(translate: [number, number]): Projection;
center(center: [number, number]): Projection;
}Event handling systems for implementing drag, zoom, and brush selection interactions.
// Drag behavior
function drag(): DragBehavior;
interface DragBehavior {
(selection: Selection): void;
on(type: string, listener: Function): DragBehavior;
subject(subject: Function): DragBehavior;
}
// Zoom behavior
function zoom(): ZoomBehavior;
interface ZoomBehavior {
(selection: Selection): void;
scaleExtent(extent: [number, number]): ZoomBehavior;
on(type: string, listener: Function): ZoomBehavior;
}
// Brush behavior
function brush(): BrushBehavior;
interface BrushBehavior {
(selection: Selection): void;
extent(extent: [[number, number], [number, number]]): BrushBehavior;
on(type: string, listener: Function): BrushBehavior;
}Number formatting utilities for displaying numeric values with customizable precision, notation, and localization.
// Format specifiers
function format(specifier: string): (n: number) => string;
function formatPrefix(specifier: string, value: number): (n: number) => string;
// Locale support
function formatLocale(definition: LocaleDefinition): Locale;
interface LocaleDefinition {
decimal: string;
thousands: string;
grouping: number[];
currency: [string, string];
percent: string;
minus: string;
nan: string;
}Time interval calculations and date/time formatting utilities for temporal data processing and visualization.
// Time intervals
const timeDay: TimeInterval;
const timeWeek: TimeInterval;
const timeMonth: TimeInterval;
const timeYear: TimeInterval;
interface TimeInterval {
(date: Date): Date;
floor(date: Date): Date;
ceil(date: Date): Date;
range(start: Date, stop: Date, step?: number): Date[];
every(step: number): TimeInterval;
}
// Time formatting
function timeFormat(specifier: string): (date: Date) => string;
function timeParse(specifier: string): (dateString: string) => Date | null;Predefined color palettes and schemes for data visualization, providing perceptually uniform, colorblind-friendly, and aesthetically pleasing color mappings.
// Categorical schemes
const schemeCategory10: readonly string[];
const schemeSet1: readonly string[];
const schemeTableau10: readonly string[];
// Sequential schemes
const schemeBlues: { [k: number]: readonly string[] };
const interpolateBlues: (t: number) => string;
const interpolateViridis: (t: number) => string;
// Diverging schemes
const schemeRdYlBu: { [k: number]: readonly string[] };
const interpolateRdYlBu: (t: number) => string;// Core types used across D3
type Primitive = string | number | boolean | null | undefined;
interface Selection<GElement extends BaseType = BaseType,
Datum = any,
PElement extends BaseType = BaseType,
PDatum = any> {
// Selection interface (comprehensive definitions in sub-docs)
}
interface Scale<Domain, Range> {
(value: Domain): Range;
domain(): Domain[];
domain(domain: Domain[]): Scale<Domain, Range>;
range(): Range[];
range(range: Range[]): Scale<Domain, Range>;
}
interface HierarchyNode<Datum = any> {
data: Datum;
depth: number;
height: number;
parent: HierarchyNode<Datum> | null;
children: HierarchyNode<Datum>[] | null;
value?: number;
x?: number;
y?: number;
}