GitHub
deepbox/plot

Basic Charts

Stateful plotting API. Create a Figure, add plots to Axes, then render to SVG or PNG. No browser or DOM required — runs entirely in Node.js using built-in rasterization. The API follows a stateful pattern: figure() creates and activates a figure, plot/scatter/bar/etc. draw onto the current axes, and show()/saveFig() produce the final output.

Figure

The top-level canvas container. Holds one or more Axes arranged freely or in a subplot grid. Default size: 640×480 pixels. Constructor accepts { width?: number, height?: number, background?: Color }. Maximum dimension: 32,768 px. Call renderSVG() or renderPNG() to produce output.

Axes

A single rectangular plotting area within a Figure. Owns all plot elements (lines, bars, markers, etc.), axis labels, title, tick marks, and legend. Created automatically when you call plot functions, or explicitly via subplot(). Methods: .setTitle(title), .setXLabel(label), .setYLabel(label), .setXTicks(ticks), .setYTicks(ticks).

PlotOptions
type PlotOptions = {  label?: string;        // Legend label for this series  color?: Color;         // Line/marker/fill color (hex, rgb, hsl, or CSS name)  linewidth?: number;    // Line width in pixels  size?: number;         // Marker size in pixels (scatter)  edgecolor?: Color;     // Edge color for bars and shapes  bins?: number;         // Number of histogram bins  vmin?: number;         // Min value for color mapping (heatmap)  vmax?: number;         // Max value for color mapping (heatmap)  extent?: { xmin, xmax, ymin, ymax };  // Data extent for heatmaps/contours  colors?: Color[];      // Array of colors for multi-series plots  levels?: number | number[];  // Contour levels  facecolor?: Color;     // Background color for axes area  colormap?: 'viridis' | 'plasma' | 'inferno' | 'magma' | 'grayscale';};
LegendOptions
type LegendOptions = {  visible?: boolean;     // Show/hide (default: true)  location?: 'upper-right' | 'upper-left' | 'lower-right' | 'lower-left';  fontSize?: number;     // Font size in pixels  padding?: number;      // Internal padding in pixels  background?: Color;    // Legend box background  borderColor?: Color;   // Legend box border};
figure
figure(opts?: { width?: number; height?: number; background?: Color }): Figure

Create a new Figure and set it as the active figure for subsequent plot calls. Default size: 640×480px with white background. All subsequent plot/scatter/bar/etc. calls operate on this figure's current axes.

gca
gca(): Axes

Get Current Axes — returns the active Axes on the current figure. If no axes exist yet, one is created automatically. Use this to set titles, labels, and ticks: gca().setTitle('My Plot').

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

Create or select a subplot in a rows×cols grid layout. index is 1-based, counted left-to-right then top-to-bottom (like MATLAB). The figure's canvas is divided into equal-sized cells. Each call returns a new Axes positioned in the corresponding grid cell. Maximum grid size: 10,000 subplots.

Parameters:
rows: number - Number of grid rows
cols: number - Number of grid columns
index: number - 1-based position in the grid (1 = top-left)
show
show(opts?: { figure?: Figure; format?: 'svg' | 'png' }): RenderedSVG | Promise<RenderedPNG>

Render the current (or specified) figure. SVG is returned synchronously as { kind: 'svg', svg: string }. PNG is returned as a Promise<{ kind: 'png', width, height, bytes: Uint8Array }> — PNG requires Node.js.

saveFig
saveFig(path: string, opts?: { figure?: Figure; format?: 'svg' | 'png' }): Promise<void>

Save the figure to a file. Format is inferred from the file extension (.svg or .png) unless overridden via opts.format. Writes directly to disk using Node.js fs.

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

Line chart connecting (x, y) points in order on the current axes. Use the label option to add a legend entry. Multiple plot() calls on the same axes overlay multiple lines. Set linewidth to control thickness and color for the line color.

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

2D scatter plot of individual points on the current axes. Each point is drawn as a filled circle. Use the size option to control marker radius and color for fill color.

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

Vertical bar chart. x positions the bar centers, height sets bar heights. Use edgecolor to add outlines and color for fill.

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

Horizontal bar chart. y positions the bar centers, width sets bar lengths. Mirror of bar() for horizontal layouts.

hist
hist(x: Tensor, bins?: number, options?: PlotOptions): void

Histogram showing the frequency distribution of values in x. Automatically bins the data into equal-width intervals. Default bins: 10. Use the bins option in PlotOptions to override.

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

Box-and-whisker plot. Shows the median (center line), Q1–Q3 interquartile range (box), whiskers extending to 1.5×IQR, and individual outlier points beyond the whiskers. Useful for comparing distributions and spotting outliers.

violinplot
violinplot(data: Tensor, options?: PlotOptions): void

Violin plot showing the full distribution shape via kernel density estimation. Combines the statistical summary of a boxplot with the smooth density curve, revealing multimodality and skewness that boxplots hide.

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

Pie chart showing proportional composition. Values are normalized to sum to 100%. Labels are displayed next to each slice. Use the colors option in PlotOptions to specify per-slice colors.

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

2D heatmap from a matrix [rows, cols]. Each cell is colored according to its value using the selected colormap. Supports viridis (default), plasma, inferno, magma, and grayscale colormaps. Use vmin/vmax to control the color range.

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

Display a matrix as an image. Alias for heatmap with identical behavior. Use the extent option to map pixel coordinates to data coordinates.

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

Contour line plot for a 2D scalar field. X and Y are coordinate grids (from meshgrid), Z is the scalar value at each grid point. Lines connect points of equal Z value. Use the levels option to specify the number of contour levels or explicit threshold values.

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

Filled contour plot — same as contour() but fills the regions between contour lines with interpolated colors from the selected colormap. Creates smoother visualizations of 2D scalar fields.

legend
legend(options?: LegendOptions): void

Show a legend on the current axes. Collects all labeled series (plot elements with the label option set) and displays them in a box. Position with location, style with fontSize, background, and borderColor.

basic-charts.ts
import { figure, subplot, plot, scatter, bar, hist, heatmap, boxplot, show, saveFig, legend, gca } from "deepbox/plot";import { tensor, linspace } from "deepbox/ndarray";// ── Line plot with legend ──figure({ width: 800, height: 400 });const x = linspace(0, 6.28, 100);const sinY = tensor(Array.from({ length: 100 }, (_, i) => Math.sin(i * 0.0628)));const cosY = tensor(Array.from({ length: 100 }, (_, i) => Math.cos(i * 0.0628)));plot(x, sinY, { color: "steelblue", linewidth: 2, label: "sin(x)" });plot(x, cosY, { color: "coral", linewidth: 2, label: "cos(x)" });gca().setTitle("Trigonometric Functions");gca().setXLabel("x (radians)");gca().setYLabel("f(x)");legend({ location: "upper-right" });await saveFig("trig.svg");// ── Subplot grid (2×2) ──figure({ width: 800, height: 600 });subplot(2, 2, 1); scatter(tensor([1,2,3,4]), tensor([2,4,3,5]), { color: "red" });subplot(2, 2, 2); bar(tensor([0,1,2,3]), tensor([4,7,2,5]), { color: "#4CAF50" });subplot(2, 2, 3); hist(tensor([1,1,2,2,2,3,3,4,5,5]), 5, { color: "purple" });subplot(2, 2, 4); heatmap(tensor([[1,2,3],[4,5,6],[7,8,9]]), { colormap: "viridis" });await saveFig("subplots.svg");await saveFig("subplots.png", { format: "png" });// ── Box plot ──figure();boxplot(tensor([2, 3, 5, 7, 8, 9, 10, 12, 15, 20, 25]));await saveFig("boxplot.svg");

Supported Color Formats

  • Hex: '#RRGGBB' or '#RRGGBBAA' — e.g., '#ff0000', '#ff000080' (50% transparent red)
  • RGB: 'rgb(255, 0, 0)' or 'rgba(255, 0, 0, 0.5)'
  • HSL: 'hsl(0, 100%, 50%)' or 'hsla(0, 100%, 50%, 0.5)'
  • Named: Any of 140 CSS color names — 'red', 'steelblue', 'forestgreen', 'coral', etc.
  • Invalid colors silently default to black