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 throughPlot::evcxr_displayand theevcxrmodule, 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_htmlandPlot::to_svgrender 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_pixelsfor an SVG host, thepixel::Capabilitiesquery API, andPlot::render_bestpicking the best tier the terminal offers.ratatui—PlotWidget, aratatuiwidget rendering any plot into aBuffer; rendered stateful with aPlotState, it becomes interactive: hit-testing through the cachedMapping, zoom and pan through aViewport, and default mouse gestures fed viaPlotState::on_mouse. Combined withpixel, the widget draws its panel as a real image (PlotWidget::graphics, emitted byGraphics::present) with the interaction chrome rendered into the image itself.serde— every spec type (plots, marks, scales, themes, frames) round-trips through serde;Documentis the versioned persistent envelope, gaps survive JSON asnull, 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. - Contour
Options - Configuration for
contour_with. - Density
Options - Configuration for
density_with. - Describe
Options - Configuration for
describe_with. - Document
- A versioned persistent plot document.
- Ecdf
Options - Configuration for
ecdf_with. - Heatmap
Options - Configuration for
heatmap_with. - Histogram2d
Options - Configuration for
hist2d_with. - Histogram
Options - Configuration for
hist_with. - Plot
State - 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, …). - Plot
Widget - A
Plotrendering into a ratatuiBuffer. - Stairs
Options - Configuration for
stairs_with. - Table
Options - Configuration for
table_with. - Theme
- The colors a plot draws with, independent of any terminal.
- Trend
Options - Configuration for
trend_with. - Violin
Options - Configuration for
violin_with.
Enums§
- Contour
Levels - How
contour_withchooses iso-line values. - Document
Kind - 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.
- Mouse
Button - 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
heatmapbut tracing iso-lines instead of shading. - contour_
with - Contour lines with caller-selected levels and colormap.
- contourf
- Filled contours: the grid drawn as a
heatmapunder a colormap split at thecontourlevels, so every band between two iso-lines is one color and the colorbar labels the levels — matplotlib’scontourf, as a composition:contour’s levels,heatmap’s drawing,Colormap::thresholdsbetween them. - contourf_
with - Filled contours with explicit options: the same
ContourOptionsascontour_with, its colormap split at the levels. - density
- A density chart: the Gaussian KDE of
valuesas 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
describetable with an optional inline histogram column: after the eight statistics, each group’s distribution asbinseighth-block glyphs scaled to its fullest bin, an empty bin blank — the sameBins::try_uniformgeometry a histogram preset would draw, as text on the band. The expansion is the statistics laid out bytableplus one centeredTextper group in a ninth band. - ecdf
- An ECDF chart: the fraction of
valuesat 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
errorintervals around eachy. - error_
bars_ asymmetric - Error bars with asymmetric intervals: each point reaches down by
minus[i]and up byplus[i]— the two-sided deviations of matplotlib’s 2×Nyerr. For absolute interval bounds, useRange::xydirectly. - heatmap
- A heatmap of a row-major grid,
columnswide: 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:
valuesbinned automatically (Sturges/Freedman–Diaconis, nice decimal edges) and drawn as contiguous bars from zero, on anIntegercount axis — a tall frame labels counts0, 1, 2, never0.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
valuesplotted 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:
valuesas 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 isBars::spans(0.0, 1.0, values)underPlot::axes(false). - stairs
- A step chart:
valuesheld flat between indices — counters, rates, states. The expansion isstat::stepsunderStepDirection::Post, drawn as a line. - stairs_
with - A step chart whose steps change where
StairsOptionssays. - table
- A stat table: row-major
valuesas column-formatted text on two band axes — row labels left, column headers below, like any band chart. - table_
with - A
tableconfigured withTableOptions; 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
tablefor 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.