package matrix
Build not yet checkedInstall
dune-project
Dependency
Authors
Maintainers
Sources
sha256=a92cbbcbe016fb19fb0a749222da0e459a9567aef3f4c7340d9bd6b71c53ed6f
sha512=6a7ab054605538bb31a2b73a1a6d093981a2704c9f0af5852221c05735290d74aca7c7282298c4d0f91e86a800e2ccd94b4918af883cd963449c758eb6b272b3
doc/matrix.charts/Matrix_charts/index.html
Module Matrix_chartsSource
Charts drawn in terminal cells.
A figure (t) is an immutable description of a chart. Its marks, such as line and bar_y, draw rows. A mark's rows are the elements of the array the program gives it, and the mark reads each row through accessors bound to its roles, such as x, y and color. A role reads quantities, floats, or categories, strings.
A role reads a scale by name. x roles read the scale "x", y roles "y" and color roles "color", unless rename names another scale. A scale read by x or y roles is a position scale, and one read by color roles a color scale. A scale of quantities is continuous (linear, log or time), and a scale of categories is a band scale. A scale maps each value to a position in [0;1], 0 at the left of an x axis and at the bottom of a y axis.
The domain of a continuous scale is fitted to the union of the values of the roles that read it. Marks that stand on zero, such as bars, widen it to 0, and on a position scale it is then rounded outward. A domain given with scale replaces the fitted one. The program keeps a view (View.t), which may give a position scale a window, and the window replaces the domain on screen. The window, or else the domain, is the scale's shown domain. The guides, axes for position scales and legends for color scales of categories, follow from the scales.
A figure is drawn in two steps. layout fits the scales, chooses the ticks, measures the labels and places the plot, the rectangle where marks draw, inside a region of cells. The result, a Layout.t, tells which value or row lies under a cell. draw writes a layout into a Matrix_grid.t at an origin. The life cycle of a chart in an interactive program usually goes like this:
- Keep the data and a view in the program's state,
View.emptyat first. - Build the figure from them each frame, lay it out at the region's size and draw it.
- On a pointer event, lay the figure out at the same size, ask the layout for the row under the pointer (
Layout.hit) or the next view (Layout.zoom,Layout.pan), and store the view.
Unless a value's doc says otherwise:
- Lengths are in cells. A value at position
plies in the cellc = min (W - 1) ⌊p W⌋of aW-cell axis and, atkdots per cell, in the dot⌊p W k⌋clamped to the dots ofc, so every point, rule and tick at one value lands in one cell;Layout.positionandLayout.dotgive them. A range ends at an edge between cells: a rect covers the cells that meet [x;x2), and a bar ends at the eighth, or the cell, nearest its value. - Accessors and format functions must be pure, since layout calls them and may call them again.
- A row is dropped when a value a position role reads is NaN, infinite or, on a log scale, not above
0. Layout skips a dropped row when it fits domains and when it draws, and a line breaks at it. - A mark inks the cells it writes, and is cut at the plot's edges. A cell has two planes, a glyph with its foreground and a background. A mark's write replaces the plane it paints, except that dots merge into a cell that holds dots of their resolution, whatever its colors, and the cell takes the later write's foreground and attributes: a cell shared by marks or rows of different colors shows all their dots in the last one's color.
- Layout accepts a region of any size from one cell and never raises because of it. A region too small for every guide gives up the title, the legends, the axis titles, the tick labels with their notes, the axis lines and the margins of
margins, in this order.
This prints a loss curve with a reference line. The line takes each loss's index as its x, and the reference line widens the y domain to include 1.0:
let losses = [| 2.0; 1.6; 1.3; 1.2; 1.1 |] in
let fig = Matrix_charts.(layer [ line ~y:Fun.id losses; hline 1.0 ]) in
let g = Matrix_grid.create ~width:60 ~height:15 () in
Matrix_charts.(draw (layout ~width:60 ~height:15 fig) g ~x:0 ~y:0);
print_string (Matrix_grid.to_ansi g)Figures
The type for figures.
Colors
A mark without a color takes the theme's next palette color, as does each category the first time it appears, in the order of the figure. Text, arrows, rules, rasters and candles take the colors their docs give instead. Only categories have legend entries.
The type for the colors of rows of type 'r.
const c is the color c for every row.
series s is the color of the category s of the color scale for every row. color pins the category's color.
cat f is the color of the category f r of the color scale for each row r.
Marks
A mark's ?dots is its resolution, in the sense of the dots it draws in a cell. `Cell draws whole-cell glyphs, `Half two dots per cell, one above the other, `Quadrant 2 by 2, `Sextant 2 by 3, and `Braille and `Octant 2 by 4. Lines and dots default to Theme.t.dots. The rows of a mark built from plain values, spark or histogram, are made by the mark, and its doc says what they are.
The type for resolutions.
The type for line patterns.
val line :
?dots:[ dots | `Steps ] ->
?dash:dash ->
?color:'r paint ->
?x:('r -> float) ->
y:('r -> float) ->
'r array ->
tline ~x ~y rows is the line through the points of rows in order. Without x, a row's x is its index. `Steps goes horizontally then vertically from point to point, in the theme's box glyphs. dash defaults to `Solid.
val line_gaps :
?dots:[ dots | `Steps ] ->
?dash:dash ->
?color:'r paint ->
?x:('r -> float) ->
y:('r -> float option) ->
'r array ->
tline_gaps ~y rows is line where a row whose y is None is dropped.
val area :
?dots:dots ->
?color:'r paint ->
?x:('r -> float) ->
?y2:('r -> float) ->
y:('r -> float) ->
'r array ->
tarea ~y rows is the region between the line of y and the line of y2, or 0 without y2. At `Cell, the default, it paints backgrounds.
val dot :
?dots:[ dots | `Density ] ->
?symbol:string ->
?color:'r paint ->
x:('r -> float) ->
y:('r -> float) ->
'r array ->
tdot ~x ~y rows is a mark at each point. At `Cell a point is symbol, the theme's point glyph by default. `Density shades each cell by the number of points in it against the fullest cell.
val rect :
?color:'r paint ->
?pattern:string list ->
?x:('r -> float) ->
?x2:('r -> float) ->
?y:('r -> float) ->
?y2:('r -> float) ->
'r array ->
trect rows is the background of the cells from x to x2 and from y to y2 of each row. An extent with neither end covers the plot, and an extent with one end covers the cells of that value. rect ~x ~x2:x fills the column of x.
With pattern, a tile of rows of glyphs one cell wide, the cells take the tile's glyphs in the rect's color in place of the background, so they show without color and a later mark's glyphs cover them. The tile repeats from the plot's top-left cell: the cell (x, y) of the plot takes the glyph x mod n of the tile's row y mod m, for m rows and a row of n glyphs. A space leaves its cell as it is. The tile [ "╱ "; " ╱"; " ╱ "; " ╱ " ] hatches.
Raises Invalid_argument if pattern has no rows or an empty row, and layout raises if a glyph of pattern does not take one cell by its width method.
val bar_y :
?dots:[ `Eighths | `Cell ] ->
?color:'r paint ->
?label:('r -> string) ->
x:('r -> string) ->
y:('r -> float) ->
'r array ->
tbar_y ~x ~y rows is a bar from 0 to y in the band of category x for each row. Rows of one category stack in row order, those above 0 upward and those below downward, and the ends of the stacks are fitted. A bar ends in an eighth of a cell at `Eighths, the default. A row's label is drawn inside its bar where it fits.
val bar_x :
?dots:[ `Eighths | `Cell ] ->
?color:'r paint ->
?label:('r -> string) ->
y:('r -> string) ->
x:('r -> float) ->
'r array ->
tbar_x ~y ~x rows is bar_y with horizontal bars, the first category at the top.
val raster :
?dots:[ `Cell | `Half | `Shade | `Glyph of string ] ->
?reduce:[ `Last | `Mean | `Max ] ->
?interpolate:[ `None | `Bilinear ] ->
x:('r -> float) ->
y:('r -> float) ->
value:('r -> float) ->
'r array ->
traster ~x ~y ~value rows colors each cell by value on the color scale. The rows in a cell reduce to the `Last, the default, the `Mean or the `Max. `Bilinear instead interpolates each cell's middle between the four rows around it, and then the rows must form a grid. `Cell, the default, paints the background, `Half two values per cell, `Shade a shade glyph by value and `Glyph g the glyph g.
val text :
?color:'r paint ->
?anchor:[ `Left | `Center | `Right ] ->
?offset:(int * int) ->
x:('r -> float) ->
y:('r -> float) ->
text:('r -> string) ->
'r array ->
ttext ~x ~y ~text rows is text written at each point, in the theme's label color by default. anchor puts the point at the text's start (`Left, the default), middle or end. offset (dx, dy) then moves the text dx cells right and dy cells down, (0, 0) by default, as a label beside a rule or after a line's last point. A text is drawn when its point lies in the plot. One that the plot's edges would cut is moved inside the plot, and one wider than the plot is not drawn, so a text shows whole or not at all.
val arrow :
?color:'r paint ->
?head:[ `Arrow | `Dot | `None ] ->
x:('r -> float) ->
y:('r -> float) ->
x2:('r -> float) ->
y2:('r -> float) ->
'r array ->
tarrow ~x ~y ~x2 ~y2 rows is a line from (x, y) to (x2, y2), in the theme's label color by default, that ends in head, `Arrow by default.
spark vs is the values of vs one per column, the newest at the right and the columns at the right of the plot. vs lists the newest first, as v :: vs builds it, and the oldest values that do not fit are left out. A value below 0 is drawn as 0. Its y domain runs from 0 to the largest of all of vs, unrounded, it reads no x scale, and its y axis shows only if axis adds it. Its rows are the elements of vs.
hline v is a horizontal line across the plot at y = v, in the theme's axis color by default. Its value is fitted.
vline v is hline for a vertical line at x = v.
The type for the prices of one period.
val candles :
?width:int ->
?hollow:bool ->
?rising:Ansi.Color.t ->
?falling:Ansi.Color.t ->
ohlc array ->
tcandles rows is a candle at each time, a body from open_ to close over a wick from low to high. A candle is width cells wide, 1 by default. A rising candle (close >= open_) is rising, green by default, and drawn hollow if hollow holds, and a falling one is falling, red by default.
Raises Invalid_argument if width is not 1 or 2.
val histogram :
?bins:[ `Count of int | `Width of float | `Edges of float array ] ->
?height:[ `Count | `Probability | `Density ] ->
?color:(float * float * float) paint ->
float array ->
thistogram vs is a bar per bin of the finite values of vs. bins splits their range into `Count n equal bins, `Count 10 by default, or into bins `Width w wide, or takes the bins between the sorted `Edges. A bin holds its lower edge, and the last one its upper edge too. height makes a bar the bin's count (`Count, the default), its share of the values (`Probability) or that share over the bin's width (`Density). Its rows are the bins (lower, upper, height) in order.
Raises Invalid_argument if `Count n has n < 1 or `Width w is not positive.
val circle :
?color:'r paint ->
x:('r -> float) ->
y:('r -> float) ->
r:('r -> float) ->
'r array ->
tcircle ~x ~y ~r rows is, for each row, the circle of center (x, y) and radius r in data units, whose points are fitted. It is drawn as an ellipse when the two axes have different scales.
Scales
A scale specification sets the properties it is given. The others take what the marks reading the scale imply, then the defaults of the constructors below. Bars, areas without y2, histograms and sparks imply zero on the scale of their quantities, except on a log scale, and a band scale read by y implies reverse. A domain given to a specification is neither widened nor rounded. A domain of no values is [0;1], or [1;10] on a log scale. A domain of one value maps every value to the position 0.5, except that a domain widened to 0 from 0 alone is [0;1]. Any other finite increasing domain, however long or short, maps each finite value it does not drop to a finite position, and each value in it to a position in [0;1].
Composing
Settings and guides are figures too. A wrapper (title, name, scale, rename, attrs, margins) applies to the figure it wraps, and a guide (axis, legend) or the frame is a child of a layer, as in layer [ line ~y data; axis ~title:"loss" "y" ]. A figure is well-formed when it has at most one title, one specification of each scale, one axis and one legend of each scale; when each scale it specifies or gives a guide is read by a role; when each axis is of a position scale and on a side along its direction, and each legend of a color scale of categories; when no scale is read by both position and color roles or by x and y roles, or by both quantities and categories, and none against the kind its specification gives; and when a third y scale has an axis with a side.
layer fs is the figures fs drawn in order, later over earlier, on shared scales.
scale n s f is f with s the specification of scale n.
rename a b f is f where every role, specification, axis and legend that names scale a names b. A figure gets a second y scale where one of its layers renames "y", as in rename "y" "volume" f.
attrs a f is f with the attributes a added to the glyphs of its marks.
margins f is f with least margins in cells, where the guides need less room, so that charts placed side by side align. inset puts that many cells between the plot and its axis lines. Each is 0 by default.
Raises Invalid_argument if one is negative.
Guides
Each position scale has an axis. An x scale's axis lies below the plot, the first y scale's to its left and the second's to its right. Each color scale of categories has a legend right of the plot, beyond a second y axis, in the room it needs. A legend `Inside a corner of the plot is drawn where it fits, over the cells of the marks under it. axis and legend replace these.
The ticks of a continuous axis lie in its shown domain, at steps of 1, 5, 2 or 2.5 times a power of ten, at powers on a log scale and at calendar boundaries on a time scale. Their number follows the axis's length, and two labels keep at least one blank cell between them. Labels share their decimals, as 0.00, 0.25, 0.50. When the values need more than seven significant digits, the labels show each value minus an offset, and when they reach 10⁶ or lie below 10⁻⁴ in magnitude, each value over a factor. The axis title is followed by that note, as +10⁶ or ×10⁶. Time labels name the coarsest unit that starts at every tick, as 2026, Mar, 3, 14:05, :09 or .25, over a context line, as Mar 2026, shown where it changes. A band axis labels every kth category for the least k of 1, 2, 5, 10, … whose labels fit.
The type for the sides of the plot.
val axis :
?side:side ->
?show:bool ->
?title:string ->
?grid:[ `None | `Ticks | `Minor of int | `Every of int ] ->
?format:(int -> float -> string) ->
?spacing:int ->
?style:Ansi.Style.t ->
?tick_style:Ansi.Style.t ->
?label_style:Ansi.Style.t ->
?title_style:Ansi.Style.t ->
?labels:(float * Ansi.span) list ->
string ->
taxis n is the axis of scale n on side, by default the side its scale's axis takes (Guides). ~show:false hides it and gives its room to the plot. A horizontal axis's title is centered below its labels, and a vertical one's is on the row of cells above the plot. grid draws gridlines across the plot at its ticks (`Ticks), also dividing each interval into n parts (`Minor n), or every n cells (`Every n), and none by default; a band axis draws them between bands. format i v labels the ith tick, of value v, in place of the labels and their note. The ticks aim to be at least spacing cells apart, 0 by default. style is the line's, tick_style the ticks', and label_style and title_style the labels' and the title's.
labels are the program's labels, such as a title at the axis's end or a cursor's value: each (v, s) writes s among the tick labels at the value v, in label_style with s's style over it, when v lies in the shown domain. On a horizontal axis s is centered on v's cell and moved inside the plot's extent, so one at the shown domain's end ends at the plot's edge; one wider than the plot is left out. On a vertical axis s is on v's row. They are placed from the last in labels to the first, and one that would come within a cell of a label already placed is left out, so of two labels that meet, the earlier is drawn only when the later is left out: a cursor's value given after a label at the axis's end hides it. A tick's label that would come within a cell of one drawn is left out, and its tick stays. On a horizontal axis they take the tick labels' row, adding it only when the axis has no ticks. Each widens a vertical axis's margin, drawn or not, so that the plot stays where it is as the view moves.
Raises Invalid_argument if `Minor n has n < 2, `Every n has n < 1 or spacing is negative. layout raises if a band scale's axis has labels.
val legend :
?side:
[ side
| `Inside of [ `Top_left | `Top_right | `Bottom_left | `Bottom_right ] ] ->
?show:bool ->
?title:string ->
?direction:[ `Rows | `Columns ] ->
string ->
tlegend n is the legend of scale n, under title. Each category has an entry, the glyph of the first mark that colors it, in its color, then its name. `Rows, the default, puts an entry on each row of cells and `Columns puts them on one. side defaults to `Right, and ~show:false hides it.
Themes
A layout reads its theme, and an element without a style of its own takes the theme's. Colors go to the grid as the theme and the figure give them, except color scales, which take the terminal's depth into account (layout).
Views
A view maps names of continuous position scales to windows, ranges of data values. A program lays its figure out under its view and replaces the view with the one View.zoom, View.pan, View.clamp, Layout.zoom or Layout.pan returns. Windows survive resizing and rebuilding, and layout ignores a window of a band scale or of a scale the figure lacks. Layout shows a window as it is, outside the domain too, and View.clamp brings it inside.
Laying out and drawing
Cells of a layout are counted from the top-left cell of its region, so a program that draws at (x, y) subtracts (x, y) from a grid cell before asking. A hit (hit) is a row found under a cell, and an overlay (overlay) a mark in cells drawn over a chart, such as pointer feedback.
type hit = {id : id;(*The mark's id.
*)row : int;(*The row's index in the mark's rows.
*)cell : int * int;(*The cell where the row was found.
*)distance : float;(*Its distance from the cell asked about.
*)
}The type for hits.
type overlay = | Crosshair of int * int(*Lines across the plot through a cell, in the theme's crosshair style.
*)| Marker of int * int(*The theme's marker glyph at a cell.
*)| Tip of {}(*A box of
*)linestwo cells beside, above or belowat, moved into the plot.`Autotakes the first of`Right,`Left,`Topand`Bottomthat the plot clips least among those that leaveatuncovered.
The type for overlays.
val layout :
?view:View.t ->
?theme:Theme.t ->
?depth:Ansi.Color.depth ->
?width_method:Matrix_text.width_method ->
width:int ->
height:int ->
t ->
Layout.tlayout f ~width ~height is f laid out in a region of width by height cells, under view, View.empty by default, with theme, Theme.dark by default, measuring text by width_method, `Unicode by default. At depth `Ansi256 color scales take the terminal's palette entries 16 to 255 in order of lightness, and at `Ansi16, `Ansi8 and `Mono they draw shade glyphs. depth defaults to `Truecolor.
Raises Invalid_argument if f is not well-formed (Composing).
draw l g ~x ~y draws l into g with its region's top-left cell at (x, y), then draws overlays in order. It writes only inside the region.
Smoothing
Each function keeps the x of every point of its array, in order, and smooths its y.
ema alpha ps keeps the first point and gives each later one alpha *. y +. (1. -. alpha) *. prev, where prev is the previous result. alpha must be in [0;1].
sma n ps gives each point the mean of the n points up to it, or of those there are, and is empty if n <= 0.
gaussian sigma ps is ps smoothed with a Gaussian kernel of standard deviation sigma points and radius ceil (3 *. sigma), its weights renormalized near the ends. It is ps if sigma <= 0..