Utilities for loading external data files and performing statistical operations, transformations, and aggregations on arrays and datasets. Essential for data preparation and analysis in visualizations.
Functions for fetching and parsing data from external sources.
/**
* Load and parse CSV file
* @param url - URL to CSV file
* @param row - Optional row transformation function
* @returns Promise resolving to array of objects
*/
function csv(url: string): Promise<DSVRowString[]>;
function csv<T>(url: string, row: (rawRow: DSVRowString, index: number, columns: string[]) => T): Promise<T[]>;
/**
* Load and parse TSV file
* @param url - URL to TSV file
* @param row - Optional row transformation function
* @returns Promise resolving to array of objects
*/
function tsv(url: string): Promise<DSVRowString[]>;
function tsv<T>(url: string, row: (rawRow: DSVRowString, index: number, columns: string[]) => T): Promise<T[]>;
/**
* Load and parse DSV file with custom delimiter
* @param url - URL to DSV file
* @param row - Optional row transformation function
* @returns Promise resolving to array of objects
*/
function dsv(delimiter: string, url: string): Promise<DSVRowString[]>;
function dsv<T>(delimiter: string, url: string, row: (rawRow: DSVRowString, index: number, columns: string[]) => T): Promise<T[]>;
/**
* Load JSON file
* @param url - URL to JSON file
* @returns Promise resolving to parsed JSON
*/
function json<T = any>(url: string): Promise<T>;
/**
* Load plain text file
* @param url - URL to text file
* @returns Promise resolving to text content
*/
function text(url: string): Promise<string>;
/**
* Load XML file
* @param url - URL to XML file
* @returns Promise resolving to XML document
*/
function xml(url: string): Promise<Document>;
/**
* Load HTML file
* @param url - URL to HTML file
* @returns Promise resolving to HTML document
*/
function html(url: string): Promise<Document>;
/**
* Load image file
* @param url - URL to image file
* @returns Promise resolving to image element
*/
function image(url: string): Promise<HTMLImageElement>;
/**
* Load SVG file
* @param url - URL to SVG file
* @returns Promise resolving to SVG document
*/
function svg(url: string): Promise<Document>;
/**
* Load file as ArrayBuffer
* @param url - URL to file
* @returns Promise resolving to ArrayBuffer
*/
function buffer(url: string): Promise<ArrayBuffer>;
/**
* Load file as Blob
* @param url - URL to file
* @returns Promise resolving to Blob
*/
function blob(url: string): Promise<Blob>;Usage Examples:
import { csv, json } from "d3";
// Load CSV data
const salesData = await csv("sales.csv", d => ({
date: new Date(d.date),
sales: +d.sales,
region: d.region
}));
// Load JSON data
const geoData = await json("countries.json");
// Error handling
try {
const data = await csv("data.csv");
} catch (error) {
console.error("Failed to load data:", error);
}Functions for parsing and formatting delimiter-separated values without network requests.
/**
* Parse CSV string into array of objects
* @param csvString - CSV string to parse
* @param row - Optional row transformation function
* @returns Array of objects
*/
function csvParse(csvString: string): DSVRowString[];
function csvParse<T>(csvString: string, row: (rawRow: DSVRowString, index: number, columns: string[]) => T): T[];
/**
* Parse CSV string into array of arrays
* @param csvString - CSV string to parse
* @param row - Optional row transformation function
* @returns Array of arrays
*/
function csvParseRows(csvString: string): string[][];
function csvParseRows<T>(csvString: string, row: (rawRow: string[], index: number) => T): T[];
/**
* Format array of objects as CSV string
* @param rows - Array of objects to format
* @param columns - Optional column names to include
* @returns CSV string
*/
function csvFormat(rows: object[], columns?: string[]): string;
/**
* Format array of arrays as CSV string
* @param rows - Array of arrays to format
* @returns CSV string
*/
function csvFormatRows(rows: string[][]): string;
/**
* Create DSV parser/formatter for custom delimiter
* @param delimiter - Field delimiter character
* @returns DSV parser/formatter object
*/
function dsvFormat(delimiter: string): DSV;
interface DSV {
parse(text: string): DSVRowString[];
parse<T>(text: string, row: (rawRow: DSVRowString, index: number, columns: string[]) => T): T[];
parseRows(text: string): string[][];
parseRows<T>(text: string, row: (rawRow: string[], index: number) => T): T[];
format(rows: object[], columns?: string[]): string;
formatRows(rows: string[][]): string;
}
/**
* Automatically infer and convert string values to appropriate types
* @param object - Object with string values to convert
* @returns Object with inferred types
*/
function autoType(object: {[key: string]: string}): any;Functions for computing summary statistics and statistical measures.
/**
* Count valid numeric values in array
* @param values - Array of values
* @param accessor - Optional value accessor function
* @returns Count of valid numbers
*/
function count<T>(values: Iterable<T>, accessor?: (d: T, i: number, data: Iterable<T>) => number | null | undefined): number;
/**
* Compute minimum value
* @param values - Array of values
* @param accessor - Optional value accessor function
* @returns Minimum value or undefined if empty
*/
function min<T>(values: Iterable<T>): T | undefined;
function min<T, U>(values: Iterable<T>, accessor: (d: T, i: number, data: Iterable<T>) => U): U | undefined;
/**
* Compute maximum value
* @param values - Array of values
* @param accessor - Optional value accessor function
* @returns Maximum value or undefined if empty
*/
function max<T>(values: Iterable<T>): T | undefined;
function max<T, U>(values: Iterable<T>, accessor: (d: T, i: number, data: Iterable<T>) => U): U | undefined;
/**
* Compute both minimum and maximum values
* @param values - Array of values
* @param accessor - Optional value accessor function
* @returns [min, max] or [undefined, undefined] if empty
*/
function extent<T>(values: Iterable<T>): [T, T] | [undefined, undefined];
function extent<T, U>(values: Iterable<T>, accessor: (d: T, i: number, data: Iterable<T>) => U): [U, U] | [undefined, undefined];
/**
* Compute sum of numeric values
* @param values - Array of values
* @param accessor - Optional value accessor function
* @returns Sum of values
*/
function sum<T>(values: Iterable<T>, accessor?: (d: T, i: number, data: Iterable<T>) => number | null | undefined): number;
/**
* Compute arithmetic mean (average)
* @param values - Array of values
* @param accessor - Optional value accessor function
* @returns Mean value or undefined if empty
*/
function mean<T>(values: Iterable<T>, accessor?: (d: T, i: number, data: Iterable<T>) => number | null | undefined): number | undefined;
/**
* Compute median (0.5-quantile)
* @param values - Array of values
* @param accessor - Optional value accessor function
* @returns Median value or undefined if empty
*/
function median<T>(values: Iterable<T>, accessor?: (d: T, i: number, data: Iterable<T>) => number | null | undefined): number | undefined;
/**
* Compute quantile (percentile) of sorted values
* @param values - Array of values
* @param p - Quantile value between 0 and 1
* @param accessor - Optional value accessor function
* @returns Quantile value or undefined if empty
*/
function quantile<T>(values: Iterable<T>, p: number, accessor?: (d: T, i: number, data: Iterable<T>) => number | null | undefined): number | undefined;
/**
* Compute variance of values
* @param values - Array of values
* @param accessor - Optional value accessor function
* @returns Variance or undefined if empty
*/
function variance<T>(values: Iterable<T>, accessor?: (d: T, i: number, data: Iterable<T>) => number | null | undefined): number | undefined;
/**
* Compute standard deviation of values
* @param values - Array of values
* @param accessor - Optional value accessor function
* @returns Standard deviation or undefined if empty
*/
function deviation<T>(values: Iterable<T>, accessor?: (d: T, i: number, data: Iterable<T>) => number | null | undefined): number | undefined;
/**
* Compute mode (most frequent value)
* @param values - Array of values
* @param accessor - Optional value accessor function
* @returns Most frequent value or undefined if empty
*/
function mode<T>(values: Iterable<T>, accessor?: (d: T, i: number, data: Iterable<T>) => T): T | undefined;Usage Examples:
import { mean, extent, sum, quantile } from "d3";
const sales = [120, 150, 180, 90, 200, 140];
console.log(mean(sales)); // 146.67
console.log(extent(sales)); // [90, 200]
console.log(sum(sales)); // 880
console.log(quantile(sales, 0.5)); // 145 (median)
// With accessor function
const data = [
{ name: "Alice", age: 25 },
{ name: "Bob", age: 30 },
{ name: "Charlie", age: 35 }
];
console.log(mean(data, d => d.age)); // 30
console.log(extent(data, d => d.age)); // [25, 35]Functions for transforming, filtering, and manipulating arrays.
/**
* Generate array of consecutive integers
* @param start - Start value (or stop if only one argument)
* @param stop - Stop value (exclusive)
* @param step - Step size (default 1)
* @returns Array of consecutive integers
*/
function range(stop: number): number[];
function range(start: number, stop: number, step?: number): number[];
/**
* Compute Cartesian product of arrays
* @param arrays - Arrays to compute product of
* @returns Array of tuples representing Cartesian product
*/
function cross<T>(...arrays: T[][]): T[][];
/**
* Merge multiple arrays into single array
* @param arrays - Arrays to merge
* @returns Flattened array
*/
function merge<T>(arrays: Iterable<T>[]): T[];
/**
* Create array of adjacent pairs from array
* @param values - Input array
* @param reducer - Optional function to transform pairs
* @returns Array of adjacent pairs
*/
function pairs<T>(values: Iterable<T>): Array<[T, T]>;
function pairs<T, U>(values: Iterable<T>, reducer: (a: T, b: T) => U): U[];
/**
* Transpose array of arrays (matrix transpose)
* @param matrix - Array of arrays to transpose
* @returns Transposed matrix
*/
function transpose<T>(matrix: T[][]): T[][];
/**
* Zip multiple arrays together
* @param arrays - Arrays to zip
* @returns Array of tuples
*/
function zip<T>(...arrays: T[][]): T[][];
/**
* Randomize order of array elements
* @param array - Array to shuffle (modified in-place)
* @param lo - Optional start index
* @param hi - Optional end index
* @returns Shuffled array
*/
function shuffle<T>(array: T[], lo?: number, hi?: number): T[];
/**
* Create shuffler function with specific random source
* @param random - Random number generator function
* @returns Shuffler function
*/
function shuffler(random: () => number): <T>(array: T[], lo?: number, hi?: number) => T[];
/**
* Sort array in ascending order
* @param values - Values to sort
* @param comparator - Optional comparison function
* @returns Sorted array
*/
function sort<T>(values: Iterable<T>, comparator?: (a: T, b: T) => number): T[];
/**
* Natural ascending comparator function
* @param a - First value
* @param b - Second value
* @returns Comparison result
*/
function ascending<T>(a: T, b: T): number;
/**
* Natural descending comparator function
* @param a - First value
* @param b - Second value
* @returns Comparison result
*/
function descending<T>(a: T, b: T): number;Functions for grouping data and performing aggregations.
/**
* Group iterable by key functions into nested Map
* @param values - Values to group
* @param keys - Key functions for grouping
* @returns Nested Map of grouped values
*/
function group<T, K>(values: Iterable<T>, key: (value: T) => K): Map<K, T[]>;
function group<T, K1, K2>(values: Iterable<T>, key1: (value: T) => K1, key2: (value: T) => K2): Map<K1, Map<K2, T[]>>;
/**
* Group iterable by key functions into nested array
* @param values - Values to group
* @param keys - Key functions for grouping
* @returns Nested array of [key, values] pairs
*/
function groups<T, K>(values: Iterable<T>, key: (value: T) => K): Array<[K, T[]]>;
/**
* Group and reduce iterable into nested Map
* @param values - Values to group and reduce
* @param reduce - Reduce function
* @param keys - Key functions for grouping
* @returns Nested Map of reduced values
*/
function rollup<T, R, K>(values: Iterable<T>, reduce: (values: T[]) => R, key: (value: T) => K): Map<K, R>;
/**
* Group and reduce iterable into nested array
* @param values - Values to group and reduce
* @param reduce - Reduce function
* @param keys - Key functions for grouping
* @returns Nested array of [key, reduced_value] pairs
*/
function rollups<T, R, K>(values: Iterable<T>, reduce: (values: T[]) => R, key: (value: T) => K): Array<[K, R]>;
/**
* Index iterable by key functions into nested Map
* @param values - Values to index
* @param keys - Key functions for indexing
* @returns Nested Map of indexed values
*/
function index<T, K>(values: Iterable<T>, key: (value: T) => K): Map<K, T>;
/**
* Sort keys by grouped values
* @param values - Values to group
* @param comparator - Comparison function for groups
* @param key - Key function for grouping
* @returns Sorted array of keys
*/
function groupSort<T, K>(values: Iterable<T>, comparator: (a: T[], b: T[]) => number, key: (value: T) => K): K[];Usage Examples:
import { group, rollup, sum, mean } from "d3";
const sales = [
{ region: "North", product: "A", amount: 100 },
{ region: "North", product: "B", amount: 150 },
{ region: "South", product: "A", amount: 200 },
{ region: "South", product: "B", amount: 80 }
];
// Group by region
const byRegion = group(sales, d => d.region);
// Map { "North" => [...], "South" => [...] }
// Group by region and product
const byRegionProduct = group(sales, d => d.region, d => d.product);
// Map { "North" => Map { "A" => [...], "B" => [...] }, ... }
// Rollup to compute sums
const totalByRegion = rollup(sales, v => sum(v, d => d.amount), d => d.region);
// Map { "North" => 250, "South" => 280 }Functions for creating histograms and binning continuous data into discrete intervals.
/**
* Create histogram bin generator with default settings
* @returns Bin generator function
*/
function bin(): BinGenerator<number, number>;
function bin<Datum>(): BinGenerator<Datum, number>;
function bin<Datum, Value>(): BinGenerator<Datum, Value>;
interface BinGenerator<Datum, Value> {
/** Generate bins for data */
(data: Datum[]): Bin<Datum, Value>[];
/** Set value accessor function */
value(accessor: (d: Datum, i: number, data: Datum[]) => Value): BinGenerator<Datum, Value>;
/** Set domain [min, max] for binning */
domain(domain: [Value, Value] | ((values: Value[]) => [Value, Value])): BinGenerator<Datum, Value>;
/** Set bin thresholds */
thresholds(thresholds: number | number[] | ((values: Value[], domain: [Value, Value]) => number[])): BinGenerator<Datum, Value>;
}
interface Bin<Datum, Value> extends Array<Datum> {
x0: Value; // Lower bound of bin
x1: Value; // Upper bound of bin
}
/**
* Generate nice threshold values for histograms
* @param values - Array of values to analyze
* @param count - Approximate number of bins desired
* @returns Array of threshold values
*/
function thresholdFreedmanDiaconis<T>(values: ArrayLike<T>, min: number, max: number): number[];
function thresholdScott<T>(values: ArrayLike<T>, min: number, max: number): number[];
function thresholdSturges<T>(values: ArrayLike<T>): number;Usage Examples:
import { bin, thresholdFreedmanDiaconis } from "d3";
const data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// Basic histogram
const histogram = bin()(data);
histogram.forEach(bin => {
console.log(`[${bin.x0}, ${bin.x1}): ${bin.length} values`);
});
// Custom bins for objects
const salesData = [{amount: 100}, {amount: 200}, {amount: 150}];
const salesHistogram = bin()
.value(d => d.amount)
.thresholds(10);
const bins = salesHistogram(salesData);Functions for finding positions and performing binary searches in sorted arrays.
/**
* Find insertion point for value in sorted array (left-biased)
* @param array - Sorted array to search
* @param x - Value to find insertion point for
* @param lo - Lower bound index (default: 0)
* @param hi - Upper bound index (default: array.length)
* @returns Index where value should be inserted
*/
function bisectLeft<T>(array: ArrayLike<T>, x: T, lo?: number, hi?: number): number;
/**
* Find insertion point for value in sorted array (right-biased)
* @param array - Sorted array to search
* @param x - Value to find insertion point for
* @param lo - Lower bound index (default: 0)
* @param hi - Upper bound index (default: array.length)
* @returns Index where value should be inserted
*/
function bisectRight<T>(array: ArrayLike<T>, x: T, lo?: number, hi?: number): number;
/**
* Default bisector (same as bisectRight)
*/
const bisect: typeof bisectRight;
/**
* Create custom bisector with accessor function
* @param accessor - Function to extract comparison value
* @returns Bisector object with left/right methods
*/
function bisector<T, U>(accessor: (d: T) => U): {
left(array: ArrayLike<T>, x: U, lo?: number, hi?: number): number;
right(array: ArrayLike<T>, x: U, lo?: number, hi?: number): number;
center(array: ArrayLike<T>, x: U, lo?: number, hi?: number): number;
};
/**
* Create custom bisector with comparator function
* @param comparator - Comparison function
* @returns Bisector object with left/right methods
*/
function bisector<T>(comparator: (a: T, b: T) => number): {
left(array: ArrayLike<T>, x: T, lo?: number, hi?: number): number;
right(array: ArrayLike<T>, x: T, lo?: number, hi?: number): number;
center(array: ArrayLike<T>, x: T, lo?: number, hi?: number): number;
};Usage Examples:
import { bisectLeft, bisectRight, bisector } from "d3";
const data = [1, 2, 4, 4, 6, 8, 10];
// Find insertion points
bisectLeft(data, 4); // 2 (before existing 4s)
bisectRight(data, 4); // 4 (after existing 4s)
// Custom bisector for objects
const sales = [{date: new Date(2023, 0, 1), amount: 100}, ...];
const dateBisector = bisector(d => d.date);
const insertIndex = dateBisector.left(sales, new Date(2023, 5, 1));Additional statistical functions for data analysis and processing.
/**
* Compute variance of numeric values
* @param values - Array of values
* @param accessor - Optional value accessor function
* @returns Sample variance
*/
function variance<T>(values: Iterable<T>, accessor?: (d: T, i: number, data: Iterable<T>) => number | null | undefined): number | undefined;
/**
* Compute standard deviation of numeric values
* @param values - Array of values
* @param accessor - Optional value accessor function
* @returns Sample standard deviation
*/
function deviation<T>(values: Iterable<T>, accessor?: (d: T, i: number, data: Iterable<T>) => number | null | undefined): number | undefined;
/**
* Compute mode (most frequent value) of values
* @param values - Array of values
* @param accessor - Optional value accessor function
* @returns Most frequent value or undefined
*/
function mode<T>(values: Iterable<T>, accessor?: (d: T, i: number, data: Iterable<T>) => any): T | undefined;
/**
* Compute quantile value at given probability
* @param values - Sorted array of values
* @param p - Probability (0-1)
* @param accessor - Optional value accessor function
* @returns Quantile value
*/
function quantile<T>(values: ArrayLike<T>, p: number, accessor?: (d: T, i: number, data: ArrayLike<T>) => number | null | undefined): number | undefined;
/**
* Compute quantiles at multiple probabilities
* @param values - Sorted array of values
* @param probabilities - Array of probabilities (0-1)
* @param accessor - Optional value accessor function
* @returns Array of quantile values
*/
function quantileSorted<T>(values: ArrayLike<T>, p: number, accessor?: (d: T, i: number, data: ArrayLike<T>) => number | null | undefined): number | undefined;
/**
* Compute cumulative sum of values
* @param values - Array of values
* @param accessor - Optional value accessor function
* @returns Array of cumulative sums
*/
function cumsum<T>(values: Iterable<T>, accessor?: (d: T, i: number, data: Iterable<T>) => number | null | undefined): number[];Usage Examples:
import { variance, deviation, quantile, cumsum } from "d3";
const scores = [85, 90, 78, 92, 88, 79, 95, 87];
// Advanced statistics
const v = variance(scores); // Sample variance
const sd = deviation(scores); // Standard deviation
const median = quantile(scores.sort((a,b) => a-b), 0.5); // Median
const q25 = quantile(scores.sort((a,b) => a-b), 0.25); // First quartile
// Cumulative sum
const running = cumsum(scores); // [85, 175, 253, ...]Functions for performing logical operations on sets and arrays.
/**
* Compute set union (all unique values from both sets)
* @param values - Iterables to compute union of
* @returns Set containing union of values
*/
function union<T>(...values: Iterable<T>[]): Set<T>;
/**
* Compute set intersection (values present in all sets)
* @param values - Iterables to compute intersection of
* @returns Set containing intersection of values
*/
function intersection<T>(...values: Iterable<T>[]): Set<T>;
/**
* Compute set difference (values in first set but not others)
* @param values - Iterables to compute difference of
* @returns Set containing difference of values
*/
function difference<T>(values: Iterable<T>, ...others: Iterable<T>[]): Set<T>;
/**
* Test whether two sets are disjoint (no common elements)
* @param a - First set
* @param b - Second set
* @returns True if sets are disjoint
*/
function disjoint<T>(a: Iterable<T>, b: Iterable<T>): boolean;
/**
* Test whether first set is subset of second
* @param a - Potential subset
* @param b - Potential superset
* @returns True if a is subset of b
*/
function subset<T>(a: Iterable<T>, b: Iterable<T>): boolean;
/**
* Test whether first set is superset of second
* @param a - Potential superset
* @param b - Potential subset
* @returns True if a is superset of b
*/
function superset<T>(a: Iterable<T>, b: Iterable<T>): boolean;// DSV row types
type DSVRowString = { [key: string]: string };
type DSVRowAny = { [key: string]: any };
// Parsed row arrays
type DSVParsedArray<T> = T[] & { columns: string[] };
// Accessor function type
type Accessor<T, R> = (datum: T, index: number, array: T[]) => R;
// Numeric accessor
type NumericAccessor<T> = (datum: T, index: number, array: T[]) => number | null | undefined;
// Value types for statistics
type Primitive = string | number | boolean | Date;
type Numeric = number | { valueOf(): number };
// Grouping key types
type GroupKey = string | number | boolean | Date;
// Comparison function type
type Comparator<T> = (a: T, b: T) => number;