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,.pngor.pdf) and throws when the two disagree. It writes withnode: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.
imshowputs 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()andlistThemes()change the colors used by new plots.
Color
typeColor specification as a CSS color string (e.g., "#ff0000", "rgb(255,0,0)").
type Color = string;LegendOptions
typeLegend display options.
readonly visible?: booleanWhether the legend should be visible
readonly location?: "upper-right" | "upper-left" | "lower-right" | "lower-left"Legend placement
readonly fontSize?: numberLegend font size in pixels
readonly padding?: numberLegend padding in pixels
readonly background?: ColorLegend background color
readonly borderColor?: ColorLegend border color
PlotOptions
typeOptions 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?: stringOptional label used by legends
readonly color?: ColorLine or marker color
readonly linewidth?: numberLine width in pixels
readonly size?: numberMarker size in pixels
readonly edgecolor?: ColorEdge color for bars and shapes
readonly bins?: numberNumber of histogram bins (overrides the bins argument if provided)
readonly vmin?: numberMinimum value for color mapping
readonly vmax?: numberMaximum 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?: ColorBackground color for axes
readonly colormap?: ColormapNameColormap 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
imshowdefault).readonly barWidth?: numberBar width in data units for
bar(default 0.8).readonly barHeight?: numberBar thickness in data units for
barh(default 0.8).
RenderedPDF
typeResult 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: Uint8ArrayPDF file data as byte array
readonly width: numberPage width in points
readonly height: numberPage height in points
RenderedPNG
typeResult 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: numberImage width in pixels
readonly height: numberImage height in pixels
readonly bytes: Uint8ArrayPNG file data as byte array
RenderedSVG
typeResult of SVG rendering containing the complete SVG document as a string.
readonly kind: "svg"Discriminator for the rendered output type
readonly svg: stringComplete SVG document as XML string
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: Figureparent: Axes | nullThe parent axes when this is a twin (null otherwise).
setTitle(title: string): voidSet the axes title text.
setXLabel(label: string): voidSet the x-axis label text.
setYLabel(label: string): voidSet the y-axis label text.
setXTicks(values: readonly number[], labels?: readonly string[]): voidSet custom x-axis tick positions and labels.
setYTicks(values: readonly number[], labels?: readonly string[]): voidSet custom y-axis tick positions and labels.
legend(options?: LegendOptions): voidShow or configure the legend for this axes.
plot(x: AnyTensor, y: AnyTensor, options?: PlotOptions): Line2DPlot a connected line series.
scatter(x: AnyTensor, y: AnyTensor, options?: PlotOptions): Scatter2DPlot unconnected points.
bar(x: AnyTensor, height: AnyTensor, options?: PlotOptions): Bar2DPlot vertical bars.
hist(x: AnyTensor, bins?: number, options?: PlotOptions): HistogramPlot a histogram.
barh(y: AnyTensor, width: AnyTensor, options?: PlotOptions): HorizontalBar2DPlot horizontal bars.
heatmap(data: AnyTensor, options?: PlotOptions): Heatmap2DPlot a heatmap for 2D data.
dendrogram(linkage: readonly LinkageRow[], nLeaves: number, options?: PlotOptions): Dendrogram2DPlot a dendrogram from a linkage matrix.
imshow(data: AnyTensor, options?: PlotOptions): Heatmap2DDisplay a matrix as an image.
contour(X: AnyTensor, Y: AnyTensor, Z: AnyTensor, options?: PlotOptions): Contour2DPlot contour lines for a 2D grid.
contourf(X: AnyTensor, Y: AnyTensor, Z: AnyTensor, options?: PlotOptions): ContourF2DPlot filled contours for a 2D grid.
boxplot(data: AnyTensor, options?: PlotOptions): BoxplotPlot a box-and-whisker summary for a 1D dataset.
violinplot(data: AnyTensor, options?: ViolinplotOptions): ViolinplotPlot 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): PiePlot a pie chart.
twinx(): AxesCreate a twin Axes that shares the x-axis but has an independent y-axis rendered on the right side.
xlim(min: number, max: number): voidSet explicit x-axis limits.
ylim(min: number, max: number): voidSet explicit y-axis limits.
grid(visible?: boolean, options?: { color?: Color; }): voidShow or hide grid lines.
annotate(text: string, x: number, y: number, options?: TextOptions): voidAdd a text annotation at data coordinates.
axhline(y: number, options?: { color?: Color; linewidth?: number; label?: string; }): voidDraw a dashed horizontal line across the axes at the given y value.
axvline(x: number, options?: { color?: Color; linewidth?: number; label?: string; }): voidDraw a dashed vertical line across the axes at the given x value.
setXScale(scale: "linear" | "log"): voidSet the x-axis scale.
setYScale(scale: "linear" | "log"): voidSet the y-axis scale.
text(x: number, y: number, s: string, options?: TextOptions): voidAdd text at data coordinates (alias of annotate, with the text as the third argument).
step(x: AnyTensor, y: AnyTensor, options?: PlotOptions & { where?: StepPosition; }): Line2DPlot a step function.
errorbar(x: AnyTensor, y: AnyTensor, yerr: AnyTensor, options?: PlotOptions): Line2DPlot error bars: the series as a line plus a vertical bar at each point.
fillBetween(x: AnyTensor, y1: AnyTensor, y2: AnyTensor, options?: PlotOptions): Line2DFill the area between two y-curves.
fill_between(x: AnyTensor, y1: AnyTensor, y2: AnyTensor, options?: PlotOptions): Line2DdeprecatedFill the area between two y-curves.
area(x: AnyTensor, y: AnyTensor, options?: PlotOptions): Line2DFilled area between a curve and y = 0.
stackedBar(x: AnyTensor, heights: readonly AnyTensor[], options?: { colors?: readonly Color[]; labels?: readonly string[]; }): voidPlot stacked vertical bars for multiple series.
groupedBar(x: AnyTensor, heights: readonly AnyTensor[], options?: { colors?: readonly Color[]; labels?: readonly string[]; }): voidPlot grouped (side-by-side) vertical bars for multiple series.
stem(x: AnyTensor, y: AnyTensor, options?: PlotOptions & { baseline?: number; }): Stem2DStem 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; }): Strip2DStrip plot: jittered categorical scatter plot.
radar(series: readonly AnyTensor[], options?: { colors?: readonly Color[]; labels?: readonly string[]; linewidth?: number; }): Radar2DRadar (spider) chart: multi-dimensional data on radial axes.
waterfall(categories: readonly string[], values: AnyTensor, options?: { positiveColor?: Color; negativeColor?: Color; totalColor?: Color; barWidth?: number; }): Waterfall2DWaterfall chart: cumulative positive/negative value changes.
quiver(x: AnyTensor, y: AnyTensor, u: AnyTensor, v: AnyTensor, options?: PlotOptions & { scale?: number; }): Quiver2DQuiver plot: vector field arrows.
polar(theta: AnyTensor, r: AnyTensor, options?: PlotOptions & { fill?: boolean; }): Polar2DPolar plot: data in polar coordinates (theta, r).
surface(xGrid: Float64Array[], yGrid: Float64Array[], zGrid: Float64Array[], options?: Plot3DOptions): Surface3D3D surface plot.
wireframe(xGrid: Float64Array[], yGrid: Float64Array[], zGrid: Float64Array[], options?: Plot3DOptions): Wireframe3D3D wireframe plot.
scatter3d(x: Float64Array, y: Float64Array, z: Float64Array, options?: Plot3DOptions): Scatter3D3D 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.
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: numberWidth in pixels.
readonly height: numberHeight in pixels.
readonly background: ColorBackground 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; }): AxesAdd a new axes to the figure and return it.
renderSVG(): RenderedSVGRender this figure to SVG.
renderPNG(): Promise<RenderedPNG>Render this figure to PNG (Node.js only).
renderPDF(): RenderedPDFRender this figure to PDF.
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
pathstring- 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
xTensoryTensoroptionsoptionalPlotOptions
scatter
function scatter(x: Tensor, y: Tensor, options?: PlotOptions): void;Plot unconnected points on the current axes.
Parameters
xTensoryTensoroptionsoptionalPlotOptions
bar
function bar(x: Tensor, height: Tensor, options?: PlotOptions): void;Plot vertical bars on the current axes.
Parameters
xTensorheightTensoroptionsoptionalPlotOptions
barh
function barh(y: Tensor, width: Tensor, options?: PlotOptions): void;Plot horizontal bars on the current axes.
Parameters
yTensorwidthTensoroptionsoptionalPlotOptions
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
ynumberoptionsoptional{ 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
xnumberoptionsoptional{ 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
xTensorheightsreadonly 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
xTensorheightsreadonly 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
xTensor- 1D tensor of sample values
binsoptionalnumber | (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. optionsoptionalPlotOptions- Styling options
boxplot
function boxplot(data: Tensor, options?: PlotOptions): void;Plot a box-and-whisker summary on the current axes.
Parameters
dataTensoroptionsoptionalPlotOptions
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
dataTensoroptionsoptionalViolinplotOptions
pie
function pie(values: Tensor, labels?: readonly string[], options?: PlotOptions): void;Plot a pie chart on the current axes.
Parameters
valuesTensorlabelsoptionalreadonly string[]optionsoptionalPlotOptions
legend
function legend(options?: LegendOptions): void;Show or configure a legend on the current axes.
Parameters
optionsoptionalLegendOptions
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
dataTensoroptionsoptionalPlotOptions
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
dataTensoroptionsoptionalPlotOptions
contour
function contour(X: Tensor, Y: Tensor, Z: Tensor, options?: PlotOptions): void;Plot contour lines for a 2D grid.
Parameters
XTensorYTensorZTensoroptionsoptionalPlotOptions
contourf
function contourf(X: Tensor, Y: Tensor, Z: Tensor, options?: PlotOptions): void;Plot filled contours for a 2D grid.
Parameters
XTensorYTensorZTensoroptionsoptionalPlotOptions
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
xGridArrayLike<ArrayLike<number>>- 2D array of x-coordinates (rows x cols)
yGridArrayLike<ArrayLike<number>>- 2D array of y-coordinates (rows x cols)
zGridArrayLike<ArrayLike<number>>- 2D array of z-values (rows x cols)
optionsoptionalimport("./plots/Surface3D").Plot3DOptions- 3D plot options (elevation, azimuth, color, etc.)
Throws
ShapeErrorIf the grids are empty, ragged, or differ in shape.
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
xGridArrayLike<ArrayLike<number>>- 2D array of x-coordinates (rows x cols)
yGridArrayLike<ArrayLike<number>>- 2D array of y-coordinates (rows x cols)
zGridArrayLike<ArrayLike<number>>- 2D array of z-values (rows x cols)
optionsoptionalimport("./plots/Surface3D").Plot3DOptions- 3D plot options (elevation, azimuth, color, etc.)
Throws
ShapeErrorIf the grids are empty, ragged, or differ in shape.
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
xArrayLike<number>- 1D array of x-coordinates
yArrayLike<number>- 1D array of y-coordinates
zArrayLike<number>- 1D array of z-coordinates
optionsoptionalimport("./plots/Surface3D").Plot3DOptions- 3D plot options (elevation, azimuth, color, size, etc.)
Throws
ShapeErrorIf the arrays differ in length.
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
rowsnumbercolsnumberindexnumberoptionsoptional{ 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
namestring- 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
namestring- 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
namestring- Palette name
indexnumber- Integer color index
Returns
stringHex color string
Throws
InvalidParameterErrorIf the palette name is unknown orindexis not an integer.
listPalettes
function listPalettes(): string[];List all available palette names.
Returns
string[]
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 });Found a mistake? Open an issue.