Skip to content

deepbox/plot

Figure API & Core Charts

Figures and axes, the state-based plotting functions, themes and palettes, and SVG, PNG and PDF output.

  • Rendering

Overview

  • There are two styles. State functions (figure(), plot(x, y), legend(), saveFig(path)) act on the current axes, and the object API (new Figure(), fig.addAxes(), ax.plot(...)) keeps explicit handles. gca() creates a figure and axes when none exist. Plot functions take tensors.
  • show() returns the figure as SVG, { svg }, synchronously. show({ format: "png" }) returns a promise. saveFig(path, { figure, format }) takes the format from the extension (.svg, .png or .pdf) and throws when the two disagree. It writes with node:fs, so it needs Node.js.
  • Rendering is plain TypeScript. PNG output draws its own grids, text and translucent colors, without a browser or a native library.
  • imshow puts row 0 at the bottom of the y axis, where matplotlib puts it at the top. Pass { origin: "upper" } to match matplotlib. setTheme(name), getTheme() and listThemes() change the colors used by new plots.

Types

6

Color

type

Color specification as a CSS color string (e.g., "#ff0000", "rgb(255,0,0)").

type Color = string;

LegendOptions

type

Legend display options.

  • readonly visible?: boolean

    Whether the legend should be visible

  • readonly location?: "upper-right" | "upper-left" | "lower-right" | "lower-left"

    Legend placement

  • readonly fontSize?: number

    Legend font size in pixels

  • readonly padding?: number

    Legend padding in pixels

  • readonly background?: Color

    Legend background color

  • readonly borderColor?: Color

    Legend border color

PlotOptions

type

Options for customizing plot appearance and behavior. Different plot types use different subsets of these options.

Supported Color Formats: - Hex: "#RGB", "#RGBA", "#RRGGBB" or "#RRGGBBAA" (e.g., "#f00", "#ff0000", "#ff000080") - RGB: "rgb(255, 0, 0)", "rgba(255, 0, 0, 0.5)" or "rgb(100% 0% 0% / 50%)" - HSL: "hsl(0, 100%, 50%)" or "hsla(0, 100%, 50%, 0.5)" - Named: "red", "blue", "forestgreen", etc. (the 148 CSS color names) and "transparent" - Anything else (including misspelled names) is drawn as black

  • readonly label?: string

    Optional label used by legends

  • readonly color?: Color

    Line or marker color

  • readonly linewidth?: number

    Line width in pixels

  • readonly size?: number

    Marker size in pixels

  • readonly edgecolor?: Color

    Edge color for bars and shapes

  • readonly bins?: number

    Number of histogram bins (overrides the bins argument if provided)

  • readonly vmin?: number

    Minimum value for color mapping

  • readonly vmax?: number

    Maximum value for color mapping

  • readonly extent?: { readonly xmin: number; readonly xmax: number; readonly ymin: number; readonly ymax: number; }

    Explicit data extent for heatmaps, images, and contour plots

  • readonly colors?: readonly Color[]

    Array of colors for multi-series plots

  • readonly levels?: number | readonly number[]

    Contour levels (number or explicit values)

  • readonly facecolor?: Color

    Background color for axes

  • readonly colormap?: ColormapName

    Colormap for heatmaps, images and contours (viridis, plasma, inferno, magma, cividis, grayscale)

  • readonly origin?: "lower" | "upper"

    Which edge of the y range shows row 0 of a heatmap or image: "lower" (default, row 0 at the bottom) or "upper" (row 0 at the top, like matplotlib's imshow default).

  • readonly barWidth?: number

    Bar width in data units for bar (default 0.8).

  • readonly barHeight?: number

    Bar thickness in data units for barh (default 0.8).

RenderedPDF

type

Result of PDF rendering containing the PDF file data. PDF rendering is only available in Node.js environments.

  • readonly kind: "pdf"

    Discriminator for the rendered output type

  • readonly bytes: Uint8Array

    PDF file data as byte array

  • readonly width: number

    Page width in points

  • readonly height: number

    Page height in points

RenderedPNG

type

Result of PNG rendering containing the image dimensions and the encoded PNG file bytes. PNG encoding is only available in Node.js environments.

  • readonly kind: "png"

    Discriminator for the rendered output type

  • readonly width: number

    Image width in pixels

  • readonly height: number

    Image height in pixels

  • readonly bytes: Uint8Array

    PNG file data as byte array

RenderedSVG

type

Result of SVG rendering containing the complete SVG document as a string.

  • readonly kind: "svg"

    Discriminator for the rendered output type

  • readonly svg: string

    Complete SVG document as XML string

Classes

2

Axes

An Axes represents a single plot area within a Figure.

Create one with fig.addAxes(). Plotting methods take 1D (or, for matrices, 2D) tensors and add a series to the axes; rendering happens when the figure is rendered. The axes is drawn inside its viewport, inset by padding pixels on every side to leave room for ticks, labels and the title.

Members (48)
  • constructor(fig: Figure, options: { readonly padding?: number; readonly facecolor?: Color; readonly viewport?: Viewport; })
  • readonly fig: Figure
  • parent: Axes | null

    The parent axes when this is a twin (null otherwise).

  • setTitle(title: string): void

    Set the axes title text.

  • setXLabel(label: string): void

    Set the x-axis label text.

  • setYLabel(label: string): void

    Set the y-axis label text.

  • setXTicks(values: readonly number[], labels?: readonly string[]): void

    Set custom x-axis tick positions and labels.

  • setYTicks(values: readonly number[], labels?: readonly string[]): void

    Set custom y-axis tick positions and labels.

  • legend(options?: LegendOptions): void

    Show or configure the legend for this axes.

  • plot(x: AnyTensor, y: AnyTensor, options?: PlotOptions): Line2D

    Plot a connected line series.

  • scatter(x: AnyTensor, y: AnyTensor, options?: PlotOptions): Scatter2D

    Plot unconnected points.

  • bar(x: AnyTensor, height: AnyTensor, options?: PlotOptions): Bar2D

    Plot vertical bars.

  • hist(x: AnyTensor, bins?: number, options?: PlotOptions): Histogram

    Plot a histogram.

  • barh(y: AnyTensor, width: AnyTensor, options?: PlotOptions): HorizontalBar2D

    Plot horizontal bars.

  • heatmap(data: AnyTensor, options?: PlotOptions): Heatmap2D

    Plot a heatmap for 2D data.

  • dendrogram(linkage: readonly LinkageRow[], nLeaves: number, options?: PlotOptions): Dendrogram2D

    Plot a dendrogram from a linkage matrix.

  • imshow(data: AnyTensor, options?: PlotOptions): Heatmap2D

    Display a matrix as an image.

  • contour(X: AnyTensor, Y: AnyTensor, Z: AnyTensor, options?: PlotOptions): Contour2D

    Plot contour lines for a 2D grid.

  • contourf(X: AnyTensor, Y: AnyTensor, Z: AnyTensor, options?: PlotOptions): ContourF2D

    Plot filled contours for a 2D grid.

  • boxplot(data: AnyTensor, options?: PlotOptions): Boxplot

    Plot a box-and-whisker summary for a 1D dataset.

  • violinplot(data: AnyTensor, options?: ViolinplotOptions): Violinplot

    Plot a violin distribution summary for a 1D dataset: a Gaussian kernel density estimate mirrored around position, with the quartiles marked.

  • pie(values: AnyTensor, labels?: readonly string[], options?: PlotOptions): Pie

    Plot a pie chart.

  • twinx(): Axes

    Create a twin Axes that shares the x-axis but has an independent y-axis rendered on the right side.

  • xlim(min: number, max: number): void

    Set explicit x-axis limits.

  • ylim(min: number, max: number): void

    Set explicit y-axis limits.

  • grid(visible?: boolean, options?: { color?: Color; }): void

    Show or hide grid lines.

  • annotate(text: string, x: number, y: number, options?: TextOptions): void

    Add a text annotation at data coordinates.

  • axhline(y: number, options?: { color?: Color; linewidth?: number; label?: string; }): void

    Draw a dashed horizontal line across the axes at the given y value.

  • axvline(x: number, options?: { color?: Color; linewidth?: number; label?: string; }): void

    Draw a dashed vertical line across the axes at the given x value.

  • setXScale(scale: "linear" | "log"): void

    Set the x-axis scale.

  • setYScale(scale: "linear" | "log"): void

    Set the y-axis scale.

  • text(x: number, y: number, s: string, options?: TextOptions): void

    Add text at data coordinates (alias of annotate, with the text as the third argument).

  • step(x: AnyTensor, y: AnyTensor, options?: PlotOptions & { where?: StepPosition; }): Line2D

    Plot a step function.

  • errorbar(x: AnyTensor, y: AnyTensor, yerr: AnyTensor, options?: PlotOptions): Line2D

    Plot error bars: the series as a line plus a vertical bar at each point.

  • fillBetween(x: AnyTensor, y1: AnyTensor, y2: AnyTensor, options?: PlotOptions): Line2D

    Fill the area between two y-curves.

  • fill_between(x: AnyTensor, y1: AnyTensor, y2: AnyTensor, options?: PlotOptions): Line2Ddeprecated

    Fill the area between two y-curves.

  • area(x: AnyTensor, y: AnyTensor, options?: PlotOptions): Line2D

    Filled area between a curve and y = 0.

  • stackedBar(x: AnyTensor, heights: readonly AnyTensor[], options?: { colors?: readonly Color[]; labels?: readonly string[]; }): void

    Plot stacked vertical bars for multiple series.

  • groupedBar(x: AnyTensor, heights: readonly AnyTensor[], options?: { colors?: readonly Color[]; labels?: readonly string[]; }): void

    Plot grouped (side-by-side) vertical bars for multiple series.

  • stem(x: AnyTensor, y: AnyTensor, options?: PlotOptions & { baseline?: number; }): Stem2D

    Stem plot: vertical lines from baseline to data points with markers.

  • strip(groups: readonly AnyTensor[], options?: { colors?: readonly Color[]; labels?: readonly string[]; size?: number; jitter?: number; }): Strip2D

    Strip plot: jittered categorical scatter plot.

  • radar(series: readonly AnyTensor[], options?: { colors?: readonly Color[]; labels?: readonly string[]; linewidth?: number; }): Radar2D

    Radar (spider) chart: multi-dimensional data on radial axes.

  • waterfall(categories: readonly string[], values: AnyTensor, options?: { positiveColor?: Color; negativeColor?: Color; totalColor?: Color; barWidth?: number; }): Waterfall2D

    Waterfall chart: cumulative positive/negative value changes.

  • quiver(x: AnyTensor, y: AnyTensor, u: AnyTensor, v: AnyTensor, options?: PlotOptions & { scale?: number; }): Quiver2D

    Quiver plot: vector field arrows.

  • polar(theta: AnyTensor, r: AnyTensor, options?: PlotOptions & { fill?: boolean; }): Polar2D

    Polar plot: data in polar coordinates (theta, r).

  • surface(xGrid: Float64Array[], yGrid: Float64Array[], zGrid: Float64Array[], options?: Plot3DOptions): Surface3D

    3D surface plot.

  • wireframe(xGrid: Float64Array[], yGrid: Float64Array[], zGrid: Float64Array[], options?: Plot3DOptions): Wireframe3D

    3D wireframe plot.

  • scatter3d(x: Float64Array, y: Float64Array, z: Float64Array, options?: Plot3DOptions): Scatter3D

    3D scatter plot.

Figure

A Figure represents the entire plotting canvas.

A new Figure has no axes; add them with Figure.addAxes. It renders to SVG, PDF, or (in Node.js) PNG.

Example
const fig = new Figure({ width: 400, height: 300 });const ax = fig.addAxes();ax.plot(tensor([0, 1, 2]), tensor([0, 1, 4]));const { svg } = fig.renderSVG();
Members (9)
  • constructor(options?: { readonly width?: number; readonly height?: number; readonly background?: Color; })
  • readonly width: number

    Width in pixels.

  • readonly height: number

    Height in pixels.

  • readonly background: Color

    Background color.

  • readonly axesList: Axes[]

    Axes in drawing order (later axes are drawn on top).

  • addAxes(options?: { readonly padding?: number; readonly facecolor?: Color; readonly viewport?: Viewport; }): Axes

    Add a new axes to the figure and return it.

  • renderSVG(): RenderedSVG

    Render this figure to SVG.

  • renderPNG(): Promise<RenderedPNG>

    Render this figure to PNG (Node.js only).

  • renderPDF(): RenderedPDF

    Render this figure to PDF.

Functions

32

show

function show(options?: { readonly figure?: Figure; readonly format?: "svg" | "png"; }): RenderedSVG | Promise<RenderedPNG>;

Parameters

optionsoptional
{ readonly figure?: Figure; readonly format?: "svg" | "png"; }

Returns

RenderedSVG | Promise<RenderedPNG>

saveFig

function saveFig(path: string, options?: { readonly figure?: Figure; readonly format?: "svg" | "png" | "pdf"; }): Promise<void>;

Save a figure to disk as SVG, PNG, or PDF.

The format is taken from options.format when given, otherwise from the file extension (.png, .pdf), and falls back to SVG for paths without an extension.

Parameters

path
string
Output file path (extension must match the format)
optionsoptional
{ readonly figure?: Figure; readonly format?: "svg" | "png" | "pdf"; }
Optional figure (default: the current figure) and format

Returns

Promise<void>

Throws

  • InvalidParameterErrorIf the path is empty, the format is unknown, or the file extension does not match the format.

plot

function plot(x: Tensor, y: Tensor, options?: PlotOptions): void;

Plot a connected line series on the current axes.

Parameters

x
Tensor
y
Tensor
optionsoptional
PlotOptions

scatter

function scatter(x: Tensor, y: Tensor, options?: PlotOptions): void;

Plot unconnected points on the current axes.

Parameters

x
Tensor
y
Tensor
optionsoptional
PlotOptions

bar

function bar(x: Tensor, height: Tensor, options?: PlotOptions): void;

Plot vertical bars on the current axes.

Parameters

x
Tensor
height
Tensor
optionsoptional
PlotOptions

barh

function barh(y: Tensor, width: Tensor, options?: PlotOptions): void;

Plot horizontal bars on the current axes.

Parameters

y
Tensor
width
Tensor
optionsoptional
PlotOptions

axhline

function axhline(y: number, options?: { color?: string; linewidth?: number; label?: string; }): void;

Draw a horizontal line across the current axes at the given y value.

Parameters

y
number
optionsoptional
{ color?: string; linewidth?: number; label?: string; }

axvline

function axvline(x: number, options?: { color?: string; linewidth?: number; label?: string; }): void;

Draw a vertical line across the current axes at the given x value.

Parameters

x
number
optionsoptional
{ color?: string; linewidth?: number; label?: string; }

stackedBar

function stackedBar(x: Tensor, heights: readonly Tensor[], options?: { colors?: readonly string[]; labels?: readonly string[]; }): void;

Plot stacked vertical bars for multiple series on the current axes.

Parameters

x
Tensor
heights
readonly Tensor[]
optionsoptional
{ colors?: readonly string[]; labels?: readonly string[]; }

groupedBar

function groupedBar(x: Tensor, heights: readonly Tensor[], options?: { colors?: readonly string[]; labels?: readonly string[]; }): void;

Plot grouped (side-by-side) vertical bars for multiple series on the current axes.

Parameters

x
Tensor
heights
readonly Tensor[]
optionsoptional
{ colors?: readonly string[]; labels?: readonly string[]; }

hist

function hist(x: Tensor, bins?: number | (PlotOptions & { bins?: number; }), options?: PlotOptions): void;

Plot a histogram on the current axes.

Parameters

x
Tensor
1D tensor of sample values
binsoptional
number | (PlotOptions & { bins?: number; })
Number of bins (default 10), or an options object that may carry bins. When an options object is passed here it is merged over the third argument.
optionsoptional
PlotOptions
Styling options

boxplot

function boxplot(data: Tensor, options?: PlotOptions): void;

Plot a box-and-whisker summary on the current axes.

Parameters

data
Tensor
optionsoptional
PlotOptions

violinplot

function violinplot(data: Tensor, options?: ViolinplotOptions): void;

Plot a violin summary on the current axes. options may carry position, width and bandwidth ("silverman", "scott" or a number) besides the usual styling options.

Parameters

data
Tensor
optionsoptional
ViolinplotOptions

pie

function pie(values: Tensor, labels?: readonly string[], options?: PlotOptions): void;

Plot a pie chart on the current axes.

Parameters

values
Tensor
labelsoptional
readonly string[]
optionsoptional
PlotOptions

legend

function legend(options?: LegendOptions): void;

Show or configure a legend on the current axes.

Parameters

optionsoptional
LegendOptions

heatmap

function heatmap(data: Tensor, options?: PlotOptions): void;

Plot a heatmap for a 2D tensor. Row 0 is drawn at the bottom of the y axis unless options.origin is "upper".

Parameters

data
Tensor
optionsoptional
PlotOptions

imshow

function imshow(data: Tensor, options?: PlotOptions): void;

Display a matrix as an image (alias of heatmap). Unlike matplotlib's imshow, row 0 is drawn at the bottom of the y axis unless options.origin is "upper".

Parameters

data
Tensor
optionsoptional
PlotOptions

contour

function contour(X: Tensor, Y: Tensor, Z: Tensor, options?: PlotOptions): void;

Plot contour lines for a 2D grid.

Parameters

X
Tensor
Y
Tensor
Z
Tensor
optionsoptional
PlotOptions

contourf

function contourf(X: Tensor, Y: Tensor, Z: Tensor, options?: PlotOptions): void;

Plot filled contours for a 2D grid.

Parameters

X
Tensor
Y
Tensor
Z
Tensor
optionsoptional
PlotOptions

surface

function surface(xGrid: ArrayLike<ArrayLike<number>>, yGrid: ArrayLike<ArrayLike<number>>, zGrid: ArrayLike<ArrayLike<number>>, options?: import("./plots/Surface3D").Plot3DOptions): void;

Create a 3D surface plot on the current axes.

Parameters

xGrid
ArrayLike<ArrayLike<number>>
2D array of x-coordinates (rows x cols)
yGrid
ArrayLike<ArrayLike<number>>
2D array of y-coordinates (rows x cols)
zGrid
ArrayLike<ArrayLike<number>>
2D array of z-values (rows x cols)
optionsoptional
import("./plots/Surface3D").Plot3DOptions
3D plot options (elevation, azimuth, color, etc.)

Throws

  • ShapeErrorIf the grids are empty, ragged, or differ in shape.
Example
import { surface } from 'deepbox/plot'; const n = 20;const grid = (f: (x: number, y: number) => number): number[][] =>  Array.from({ length: n }, (_, i) =>    Array.from({ length: n }, (_, j) => f(-2 + (4 * i) / (n - 1), -2 + (4 * j) / (n - 1)))  );surface(  grid((x) => x),  grid((_, y) => y),  grid((x, y) => Math.sin(Math.hypot(x, y))));

wireframe

function wireframe(xGrid: ArrayLike<ArrayLike<number>>, yGrid: ArrayLike<ArrayLike<number>>, zGrid: ArrayLike<ArrayLike<number>>, options?: import("./plots/Surface3D").Plot3DOptions): void;

Create a 3D wireframe plot on the current axes.

Parameters

xGrid
ArrayLike<ArrayLike<number>>
2D array of x-coordinates (rows x cols)
yGrid
ArrayLike<ArrayLike<number>>
2D array of y-coordinates (rows x cols)
zGrid
ArrayLike<ArrayLike<number>>
2D array of z-values (rows x cols)
optionsoptional
import("./plots/Surface3D").Plot3DOptions
3D plot options (elevation, azimuth, color, etc.)

Throws

  • ShapeErrorIf the grids are empty, ragged, or differ in shape.
Example
import { wireframe } from 'deepbox/plot'; const x = [[0, 1], [0, 1]];const y = [[0, 0], [1, 1]];const z = [[0, 1], [1, 2]];wireframe(x, y, z, { color: '#333333', elevation: 45 });

scatter3d

function scatter3d(x: ArrayLike<number>, y: ArrayLike<number>, z: ArrayLike<number>, options?: import("./plots/Surface3D").Plot3DOptions): void;

Create a 3D scatter plot on the current axes.

Parameters

x
ArrayLike<number>
1D array of x-coordinates
y
ArrayLike<number>
1D array of y-coordinates
z
ArrayLike<number>
1D array of z-coordinates
optionsoptional
import("./plots/Surface3D").Plot3DOptions
3D plot options (elevation, azimuth, color, size, etc.)

Throws

  • ShapeErrorIf the arrays differ in length.
Example
import { scatter3d } from 'deepbox/plot';scatter3d([1, 2, 3], [4, 5, 6], [7, 8, 9], { color: 'red' });

figure

function figure(options?: { readonly width?: number; readonly height?: number; readonly background?: Color; }): Figure;

Create a new figure and set it as current. The figure starts with one axes that fills it (default size 320 x 240; new Figure() defaults to 640 x 480).

Parameters

optionsoptional
{ readonly width?: number; readonly height?: number; readonly background?: Color; }

Returns

Figure

gca

function gca(): Axes;

Get the current axes, creating one if needed.

Returns

Axes

subplot

function subplot(rows: number, cols: number, index: number, options?: { readonly padding?: number; readonly facecolor?: Color; }): Axes;

Create a subplot in a rows x cols grid on the current figure and make it the current axes. Positions are numbered from 1, row by row, starting at the top left. Asking again for a position that already has a subplot returns that axes (and ignores options). The empty axes that figure() creates is dropped when the first subplot is added.

Parameters

rows
number
cols
number
index
number
optionsoptional
{ readonly padding?: number; readonly facecolor?: Color; }

Returns

Axes

getTheme

function getTheme(): PlotTheme;

Get the current plot theme. The returned object is frozen.

Returns

PlotTheme

listThemes

function listThemes(): readonly string[];

List available theme names.

Returns

readonly string[]

resetTheme

function resetTheme(): void;

Reset the theme to default.

setTheme

function setTheme(name: string): void;

Set the global plot theme. Figures and axes created afterwards use it for their default colors and font sizes; existing ones are not restyled.

Parameters

name
string
Theme name: "default", "dark", "paper", or "presentation"

Throws

  • InvalidParameterErrorIf the theme name is unknown.

getPalette

function getPalette(name: string): readonly string[];

Get a named color palette.

Parameters

name
string
Palette name (tab10, Set1, Set2, Paired, viridis, plasma, inferno, magma, cividis)

Returns

readonly string[]A new array of hex color strings; changing it does not affect the palette

Throws

  • InvalidParameterErrorIf the palette name is unknown.

getPaletteColor

function getPaletteColor(name: string, index: number): string;

Get a color from a named palette by index (wraps around in both directions, so index -1 is the last color).

Parameters

name
string
Palette name
index
number
Integer color index

Returns

stringHex color string

Throws

  • InvalidParameterErrorIf the palette name is unknown or index is not an integer.

listPalettes

function listPalettes(): string[];

List all available palette names.

Returns

string[]

plot-basic.ts
import { figure, gca, saveFig, setTheme, show } from "deepbox/plot";import { tensor } from "deepbox/ndarray"; setTheme("paper");const fig = figure({ width: 800, height: 400 });const ax = gca(); const x = tensor([1, 2, 3, 4]);ax.plot(x, tensor([2, 3, 5, 4]), { color: "#0f766e", label: "trend" });ax.bar(x, tensor([1, 2, 2, 3]), { color: "rgba(148, 163, 184, 0.5)" });ax.legend(); console.log(show({ figure: fig }).svg.length > 0);await saveFig("example.svg", { figure: fig });