Skip to main content

Crate malevich

Crate malevich 

Source
Expand description

Terminal plotting: a small grammar of marks, honest axes, millions of points.

Eight marks (Line, Points, Bars, Area, Cells, Range, Rule, Text) compose over shared scales into the basic chart catalog; presets like line(), hist, box_plot, and violin are one-line fronts over that grammar. Large series aggregate to the raster before drawing (M4 — pixel-exact for lines), axes use extended-Wilkinson tick placement with exact-decimal labels, and everything renders to a plain String — colored for your terminal via Frame::detect, deterministic via Frame::plain.

use malevich::{Frame, Line, Plot, Rule};

let steps: Vec<f64> = (0..100).map(f64::from).collect();
let loss: Vec<f64> = steps.iter().map(|s| 4.0 * (-0.05 * s).exp() + 0.4).collect();
let chart = Plot::new()
    .layer(Line::xy(&steps[..], &loss[..]).label("loss"))
    .layer(Rule::h(0.5).label("target"))
    .title("training");
println!("{}", chart.render(&Frame::plain(60, 14)));

A plot is a plain value: Clone + Send + Sync, no global state, rendering is a pure function of plot and frame. Plot::render never fails — it sheds what it cannot draw — so building a plot inline needs no error handling. For a spec that arrives from deserialization or configuration, Plot::validate and Plot::try_render report the first problem as a typed Error instead.

§Failure model

Functions that return Result are the strict boundary: invalid data shapes, configuration, numeric domains, and bounded resource requests return a typed Error rather than asserting. A try_ name distinguishes that checked twin when the same operation also has a convenience form, such as Cells::matrix / Cells::try_matrix and Plot::render / Plot::try_render. The _with suffix means “configured with an options value”; its return type, not the suffix, states whether the call is fallible. Plain mark constructors and one-call presets may panic on their documented programmer invariants, such as unequal paired channels. Infallible rendering is intentionally different: it sheds malformed retained content and excessive output instead of panicking.

The modules follow the concepts (each defined in the repository’s docs/terminology.md): mark for the primitives, stat for online accumulators, reducers, and batch transforms, scale for ticks and colormaps, render for the subpixel surface and charsets, stream for live charts, data for the ingestion rim.

The gallery in EXAMPLES.md shows every chart type with its source, and cargo run --example showcase renders a colored tour in your terminal.

§Features

  • evcxr — rich display for Evcxr Jupyter notebooks through Plot::evcxr_display and the evcxr module, whose stdout protocol and card colors let a crate draw its own types on the same background. The cards themselves need no feature: Plot::to_html and Plot::to_svg render the cell grid for any host that draws with HTML or SVG.
  • ndarray — one-dimensional arrays and views plot directly; contiguous storage is zero-copy.
  • pixel — the plot panel as a real image (sixel, kitty graphics, or iTerm2 inline PNG) with text chrome around it: Plot::render_pixels, Plot::to_svg_pixels for an SVG host, the pixel::Capabilities query API, and Plot::render_best picking the best tier the terminal offers.
  • ratatui — PlotWidget, a ratatui widget rendering any plot into a Buffer; rendered stateful with a PlotState, it becomes interactive: hit-testing through the cached Mapping, zoom and pan through a Viewport, and default mouse gestures fed via PlotState::on_mouse. Combined with pixel, the widget draws its panel as a real image (PlotWidget::graphics, emitted by Graphics::present) with the interaction chrome rendered into the image itself.
  • serde — every spec type (plots, marks, scales, themes, frames) round-trips through serde; Document is the versioned persistent envelope, gaps survive JSON as null, and function-backed lines refuse to serialize rather than lie.

Re-exports§

pub use mark::Align;
pub use mark::Area;
pub use mark::Bars;
pub use mark::Cells;
pub use mark::Dash;
pub use mark::Line;
pub use mark::LineStyle;
pub use mark::Mark;
pub use mark::PointStyle;
pub use mark::Points;
pub use mark::Range;
pub use mark::Rule;
pub use mark::Text;
pub use plot::Frame;
pub use plot::Grid;
pub use plot::Mapping;
pub use plot::Panel;
pub use plot::Plot;
pub use plot::Viewport;
pub use render::Charset;
pub use render::Color;
pub use render::ColorMode;
pub use render::Raster;
pub use render::RasterCell;
pub use scale::Scale;

Modules§

data
Data ingestion: the rim where anything series-shaped becomes a Series.
evcxr
Evcxr notebook output: the stdout protocol, and the card colors.
mark
Marks: the geometric primitives that draw data.
pixel
Pixel graphics: the plot panel as a real image over sixel, kitty, or iTerm2.
plot
The plot pipeline: retained descriptions, frames, and rendering.
render
Rendering: the subpixel surface, charset codecs, and string encoders.
scale
Scales: mappings from data domain to raster range, and their ticks.
stat
Statistical transforms: aggregation that runs before scales see the data.
stream
Streaming: a concurrent sliding window and a flicker-free repaint handle.

Structs§

BoxOptions
Configuration for box_plot_with.
ContourOptions
Configuration for contour_with.
DensityOptions
Configuration for density_with.
DescribeOptions
Configuration for describe_with.
Document
A versioned persistent plot document.
EcdfOptions
Configuration for ecdf_with.
HeatmapOptions
Configuration for heatmap_with.
Histogram2dOptions
Configuration for hist2d_with.
HistogramOptions
Configuration for hist_with.
PlotState
The interaction state of one plot pane, threaded through render_stateful_widget — the ratatui idiom for widget state the host queries and feeds (ListState, TableState, …).
PlotWidget
A Plot rendering into a ratatui Buffer.
StairsOptions
Configuration for stairs_with.
TableOptions
Configuration for table_with.
Theme
The colors a plot draws with, independent of any terminal.
TrendOptions
Configuration for trend_with.
ViolinOptions
Configuration for violin_with.

Enums§

ContourLevels
How contour_with chooses iso-line values.
DocumentKind
The payload carried by a Document.
Error
Why a plot/grid spec or render request is invalid.
Mouse
Backend-neutral mouse input, in terminal cell coordinates.
MouseButton
A mouse button, in the vocabulary of Mouse.

Functions§

bar
A bar chart: one labeled bar per category, rising from zero.
box_plot
Box plots: one five-number box per category (type-7 quartiles, Tukey whiskers), with outliers as dots.
box_plot_with
Box plots with a chosen whisker rule — the 5th to 95th percentile, the full range, a wider Tukey reach.
contour
Contour lines of a row-major grid (row 0 at the bottom), like heatmap but tracing iso-lines instead of shading.
contour_with
Contour lines with caller-selected levels and colormap.
contourf
Filled contours: the grid drawn as a heatmap under a colormap split at the contour levels, so every band between two iso-lines is one color and the colorbar labels the levels — matplotlib’s contourf, as a composition: contour’s levels, heatmap’s drawing, Colormap::thresholds between them.
contourf_with
Filled contours with explicit options: the same ContourOptions as contour_with, its colormap split at the levels.
density
A density chart: the Gaussian KDE of values as a smooth line.
density_with
A Gaussian KDE evaluated at a caller-selected number of positions, with the KDE’s own options — a bandwidth rule, bounds that keep a latency density above zero, a cumulative form.
describe
A summary table: the first look before any chart — one row per group, eight fixed columns (count mean sd min p25 p50 p75 max).
describe_with
A describe table with an optional inline histogram column: after the eight statistics, each group’s distribution as bins eighth-block glyphs scaled to its fullest bin, an empty bin blank — the same Bins::try_uniform geometry a histogram preset would draw, as text on the band. The expansion is the statistics laid out by table plus one centered Text per group in a ninth band.
ecdf
An ECDF chart: the fraction of values at or below each value, as a step line from 0 to 1.
ecdf_with
An empirical CDF with an optional Dvoretzky–Kiefer–Wolfowitz confidence band: the finite-sample envelope F̂ ± √(ln(2/α)/2n), clipped to [0, 1], stepped exactly like the curve and drawn through the existing band mark.
error_bars
Error bars: points with symmetric error intervals around each y.
error_bars_asymmetric
Error bars with asymmetric intervals: each point reaches down by minus[i] and up by plus[i] — the two-sided deviations of matplotlib’s 2×N yerr. For absolute interval bounds, use Range::xy directly.
heatmap
A heatmap of a row-major grid, columns wide: two vertical color samples per cell (an averaged shade-ramp glyph in plain output), with a colorbar legending the value range. Row 0 is the bottom row.
heatmap_with
A heatmap with a caller-selected color presentation — a named or custom Colormap, optionally centered for signed data.
hist
A histogram: values binned automatically (Sturges/Freedman–Diaconis, nice decimal edges) and drawn as contiguous bars from zero, on an Integer count axis — a tall frame labels counts 0, 1, 2, never 0.5.
hist2d
A 2D histogram: point density on a uniform grid over the data’s extent, with a colorbar legending the counts.
hist2d_with
A 2D histogram with caller-selected grid geometry and color presentation.
hist_with
A histogram with a caller-selected automatic bin cap, normalization, and accumulation.
line
A line chart of values plotted against their indices.
quiver
A vector field: one arrow per point, from (x[i], y[i]) along (u[i], v[i]).
scatter
A scatter chart of the points (x[i], y[i]).
sparkline
A sparkline: values as bars from zero, one per value, in a frame with no axes — the strip beside a table row, the dashboard glance. Eighth-block fills give eight levels in one row; a gap (NaN) stays blank, and so does a series of zeros. More values than columns thin to the bar farthest from zero per column, so a spike survives. The expansion is Bars::spans(0.0, 1.0, values) under Plot::axes(false).
stairs
A step chart: values held flat between indices — counters, rates, states. The expansion is stat::steps under StepDirection::Post, drawn as a line.
stairs_with
A step chart whose steps change where StairsOptions says.
table
A stat table: row-major values as column-formatted text on two band axes — row labels left, column headers below, like any band chart.
table_with
A table configured with TableOptions; the defaults reproduce the plain preset exactly.
trend
A scatter with its least-squares trend line (Fit: slope, intercept, and R² are one call away on the same accumulator). Degenerate data (fewer than two distinct x) draws the points alone.
trend_with
A scatter with its trend line and an optional confidence band around the mean response, drawn through the existing band mark (Area::between).
try_table
Fallible counterpart to table for data-driven shapes.
violin
Violin plots: one mirrored density per category, each scaled to the same width.
violin_with
Violin plots with a caller-selected KDE sample count and KDE options.

Type Aliases§

Result
A Result whose error is malevich’s Error.