plotsdocs
A collection of building blocks for plotting. There are lots of options---take a look through this module. They are roughly grouped as follows.
Base class:
plot: Every plot object inherits from this one. See this class for methods, properties, and shortcut operators available with every plot object.
Data plots:
scatterscatter3lineline3imageheatmapfunction2vfunction2cfunction2histogram2progressbarshistogramcolumnsvistogramcandlesboxeshilbertcalendarweekstable
Furnishing plots:
textborderaxescolorbar
Arrangement plots:
blankhstackvstackdstackdstack2wrapcenter
Types:
Side: What anaxesdraws along one of its four sides.Direction: Which way along the screen acolorbarruns.RuleandAlign: What atabledraws between its cells, and where a value sits within one.
The third stacking operation, tstack, arranges plots in time rather than
across the screen, and lives with the rest of the animation machinery in
matthewplotlib.animations.
The forms the data itself may arrive in are named in matthewplotlib.data;
Orientation, which the plots drawn either way about take, in
matthewplotlib.core with the drawing routine that reads it.
plot
:
source
docs
Abstract base class for all plot objects.
A plot is essentially a 2D grid of coloured characters. This class provides the core functionality for rendering and composing plots. It is not typically instantiated directly, but it's useful to know its properties and methods.
window: window | None = None
:
class-attribute
instance-attribute
source
docs
The interval of data the plot covers on each axis, and the rectangle of character cells it covers them with. None for a plot with no coordinates.
renderstr() -> str
:
source
docs
Convert the plot into a string for printing to the terminal.
Note: plot.renderstr() is equivalent to str(plot).
clearstr() -> str
:
source
docs
Convert the plot into a string that, if printed immediately after plot.renderstr(), will clear that plot from the terminal.
Like every string in this library, the result is shaped for a plain
print: it erases the plot and then steps one row above it, so the
newline print appends leaves the cursor where the plot began, ready
to be overdrawn. Printing it with end="" instead leaves the cursor a
row high, and in an animation loop the plot then climbs the screen one
row per frame.
Requires a spare row above the plot. If the plot begins on the terminal's first row there is nowhere to step, and the redraw lands one row lower.
Erases the plot's own rows and nothing else, so anything on the screen below the plot survives. That costs a few bytes per row rather than a single erase-to-end-of-screen, which is nothing beside the redraw that follows.
Rows, though, and not columns: each row is erased margin to margin, so
anything sitting to the right of the plot goes with it. A differential
redraw (plot - prev) is careful about that boundary where this is not.
See the erase-granularity note.
renderimg(upscale: int = 1, downscale: int = 1, bgcolor: ColorLike | None = None) -> np.ndarray
:
source
docs
Convert the plot into an RGBA array for rendering with Pillow.
saveimg(filename: str, upscale: int = 1, downscale: int = 1, bgcolor: ColorLike | None = None)
:
source
docs
Render the plot as an RGBA image and save it as a PNG file at the path
filename.
updatestr(prev: plot | None) -> str
:
source
docs
Convert the plot into a string that, if printed when the cursor is just
below prev (i.e. immediately after printing prev), updates the
terminal to show this plot instead -- repainting only the cells that
differ from prev, and leaving the cursor just below this plot.
This is the fast path for animation: redrawing a whole frame re-emits every cell, while this re-emits only what changed, which can be far fewer bytes over a slow connection.
Inputs:
- prev : plot | None. The plot currently on screen. Pass None for the first frame of an animation, when the screen is still empty, and the whole plot is rendered. A plot of a different size is fine: the overlapping region is still diffed, while the rows and columns only one of them covers are painted or erased as needed.
As everywhere in this library the result is shaped for a plain print.
See CharArray.to_ansi_diff_str for the precise cursor contract.
__sub__(other: plot | None) -> str
:
source
docs
Operator shortcut for a differential redraw: the string that updates the
terminal from other to self in place.
Subtracting None means there is nothing on screen yet, so the whole plot is drawn. That makes every frame of an animation the same statement:
prev = None
for frame in frames:
print(frame - prev)
prev = frame
Compare -plot (clear) and str(plot) (full redraw). See updatestr.
__add__(other: plot) -> hstack
:
source
docs
Operator shortcut for horizontal stack.
plot1 + plot2 ==> hstack(plot1, plot2) ==> plot1 plot2
When combining with vertical stacking, note that / binds before +,
but | binds after:
plot1 / plot2 + plot3 / plot4
==> hstack(vstack(plot1, plot2), vstack(plot3, plot4))
==> plot1 plot3
plot2 plot4
plot1 + plot2 | plot3 + plot4
==> vstack(hstack(plot1, plot2), hstack(plot3, plot4))
==> plot1 plot3
plot2 plot4
__truediv__(other: plot) -> vstack
:
source
docs
High-precedence operator shortcut for vertical stack.
plot1 / plot2 ==> vstack(plot1, plot2) ==> plot1
plot2
When combining with horizontal stacking, note that / binds before
+:
plot1 / plot2 + plot3 / plot4
==> plot1 plot3
plot2 plot4
For a version that binds after +, see |.
__or__(other: plot) -> vstack
:
source
docs
Low-precedence operator shortcut for vertical stack.
plot1 | plot2 ==> vstack(plot1, plot2) ==> plot1
plot2
When combining with horizontal stacking, note that | binds after +:
plot1 + plot2 | plot3 + plot4
==> plot1 plot3
plot2 plot4
For a version that binds before +, see /.
scatter
:
source
docs
Bases: plot
Render a scatterplot using a grid of braille unicode characters.
Each character cell in the plot corresponds to a 2x4 grid of sub-pixels, represented by braille dots.
Inputs:
- series : Series. X Y data, for example a tuple (xs, ys) or triple (xs, ys, cs) where cs is a ColorLike or a list of RGB triples. See documentation for more examples.
- *etc. Further series.
- xrange : optional (number, number).
The x-axis limits
(xmin, xmax). If not provided, the limits are inferred from the min and max x-values in the data. - yrange : optional (number, number).
The y-axis limits
(ymin, ymax). If not provided, the limits are inferred from the min and max y-values in the data. - width : int (default: 30). The width of the plot in characters. The effective pixel width will be 2 * width.
- height : int (default: 10). The height of the plot in rows. The effective pixel height will be 4 * height.
scatter3
:
source
docs
Bases: plot
Scatter plot representing a 3d point cloud.
- series : Series3. X Y Z data, for example a triple (xs, ys, zs) or quad (xs, ys, zs, cs) where cs is a ColorLike or a list of RGB triples. See documentation for more examples.
- *etc.: Series3 Further series.
- camera_position: float[3] (default: [0. 0. 2.]). The position at which the camera is placed.
- camera_target: float[3] (default: [0. 0. 0.]). The position towards which the camera is facing. Should be distinct from camera position. The default is that the camera is facing towards the origin.
- scene_up: float[3] (default: [0. 1. 0.]). The unit vector designating the 'up' direction for the scene. The default is the positive Y direction. Should not have the same direction as camera_target - camera_position.
- vertical_fov_degrees: float (default 90). Vertical field of view. Points within a vertical cone of this angle are projected into the viewing area. The horizontal field of view is then determined based on the aspect ratio.
- aspect_ratio: optional float. Aspect ratio for the set of points, as a fraction (W:H represented as W/H). If not provided, uses W=width, H=2*height, which is uniform given the resolution of the plot.
- width : int. The number of character columns in the plot.
- height : int. The number of character rows in the plot.
Projected coordinates are not the data's own, so this is not a scatter
and axes does not take it: there is nothing meaningful to label an axis
with.
TODO:
- Maybe allow configurable xyz ranges with clipping prior to projection?
line
:
source
docs
Bases: plot
Render a line plot by connecting a sequence of points, using a grid of braille unicode characters.
Each character cell in the plot corresponds to a 2x4 grid of sub-pixels, represented by braille dots.
Inputs:
- series : Series. X Y data, for example a tuple (xs, ys) or triple (xs, ys, cs) where cs is a ColorLike or a list of RGB triples. See documentation for more examples.
- *etc. Further series. Each is a separate line: the end of one is not joined to the start of the next.
- xrange : optional (number, number).
The x-axis limits
(xmin, xmax). If not provided, the limits are inferred from the min and max x-values in the data. - yrange : optional (number, number).
The y-axis limits
(ymin, ymax). If not provided, the limits are inferred from the min and max y-values in the data. - width : int (default: 30). The width of the plot in characters. The effective pixel width will be 2 * width.
- height : int (default: 10). The height of the plot in rows. The effective pixel height will be 4 * height.
- thickness : float (default: 1.0). How wide to draw the line, in dots. Corners between segments are filled and the ends are rounded.
A point with a non-finite coordinate breaks the line, so that one series can be drawn as several disconnected strokes. Colors are interpolated along each segment, so a series with a color per point comes out as a gradient.
line3
:
source
docs
Bases: plot
Render a wireframe by connecting a sequence of 3d points, seen from a camera.
Inputs:
- series : Series3. X Y Z data, for example a triple (xs, ys, zs) or quad (xs, ys, zs, cs) where cs is a ColorLike or a list of RGB triples. See documentation for more examples.
- *etc.: Series3 Further series. Each is a separate line: the end of one is not joined to the start of the next.
- camera_position: float[3] (default: [0. 0. 2.]). The position at which the camera is placed.
- camera_target: float[3] (default: [0. 0. 0.]). The position towards which the camera is facing. Should be distinct from camera position. The default is that the camera is facing towards the origin.
- scene_up: float[3] (default: [0. 1. 0.]). The unit vector designating the 'up' direction for the scene. The default is the positive Y direction. Should not have the same direction as camera_target - camera_position.
- vertical_fov_degrees: float (default 90). Vertical field of view. Points within a vertical cone of this angle are projected into the viewing area. The horizontal field of view is then determined based on the aspect ratio.
- aspect_ratio: optional float. Aspect ratio for the scene, as a fraction (W:H represented as W/H). If not provided, uses W=width, H=2*height, which is uniform given the resolution of the plot.
- width : int. The number of character columns in the plot.
- height : int. The number of character rows in the plot.
- thickness : float (default: 1.0). How wide to draw the line, in dots. Corners between segments are filled and the ends are rounded.
A point with a non-finite coordinate breaks the line, which is how a mesh of several separate wires is drawn in one call. A segment reaching behind the camera is cut off in front of it, and one entirely behind the camera is not drawn.
image
:
source
docs
Bases: plot
Render a small image or 2d array using a grid of unicode half-block characters.
Represents an image by mapping pairs of vertically adjacent pixels to the foreground and background colors of a single character cell (this effectively doubles the vertical resolution in the terminal).
Inputs:
-
im : float[h,w,3] | int[h,w,3] | float[h,w] | int[h,w]. The image data. Without a colormap, an array-like matching any of the following formats:
float[h,w,3]: A 2D array of RGB triples of floats in range [0,1].int[h,w,3]: A 2D array of RGB triples of ints in range [0,255].float[h,w]: A 2D array of scalars in the range [0,1], treated as greyscale (uniform colorisation).int[h,w]: A 2D array of ints in the range [0,255], treated as greyscale (uniform colorisation).
With a colormap, the input may instead be any array accepted by that function, provided the colormap returns an RGB image of shape [h,w,3].
-
colormap : optional ColorMap. Applied to the input before its colour shape is validated. The colormaps provided by this library map (batches of) scalars to (batches of) RGB triples, such as:
- continuous colormaps like
viridis : float[...] -> uint8[...,3], and - discrete colormaps like
pico8 : int[...] -> uint8[...,3].
A custom colormap may consume any array data but must return an RGB image of shape [h,w,3].
- continuous colormaps like
-
xrange : optional (number, number). The data coordinates at the left and the right edges of the image. By default the image carries no horizontal coordinate, and so cannot be given an axis or overlaid on another plot.
- yrange : optional (number, number). The data coordinates at the bottom and the top edges of the image. By default the image carries no vertical coordinate.
Since each character cell holds two pixels, an image with an odd number of pixel rows leaves the bottom half of its last row blank. Such an image cannot be given coordinates, since its rectangle would claim half a cell more than the picture covers.
A grid of values on any other scale is a heatmap, which normalises them
onto this one and keeps the interval it used, so that the picture can be
given a colorbar over the same numbers.
heatmap
:
source
docs
Bases: image
Render a grid of values, colouring each by where it falls in an interval.
The values are normalised onto the range 0.0 to 1.0 and handed to a
colormap, so that the caller does not scale them by hand and the colours
mean the same thing from one plot to the next. The interval is kept as
vrange, so that a colorbar can be drawn over the same numbers.
Inputs:
- values : number[h, w]. The value at each pixel, the first row at the top.
- colormap : optional ColorMap. Maps each normalised value onto its colour. By default the values come out as shades of grey, black at the bottom of the interval and white at the top.
-
vrange : optional (number, number). The interval of values the colormap covers. Values outside it saturate at the nearest end. By default the interval runs from the lowest to the highest value in the grid, so that the colours span the data.
Given descending, the scale turns around:
vrange=(1, 0)colours the low values the way the high values would have been coloured. * xrange : optional (number, number). The data coordinates at the left and the right edges of the grid. By default the heatmap carries no horizontal coordinate, and so cannot be given an axis or overlaid on another plot. * yrange : optional (number, number). The data coordinates at the bottom and the top edges of the grid. By default the heatmap carries no vertical coordinate.
Since each character cell holds two pixels, a grid with an odd number of rows leaves the bottom half of its last row blank, and cannot be given coordinates.
Where every value is the same, they all come out at the bottom of the
colormap, since there is no interval for the colours to span. An explicit
vrange covering no interval is an error rather than a guess.
A value that is not a number is left out of an inferred interval, and comes out at the bottom of the colormap wherever it appears. Infinities saturate at the ends like any other value beyond the interval.
A grid of colours, of palette indices, or of values already scaled onto
the range 0.0 to 1.0 is an image rather than a heatmap: those need no
interval, and carry no colour scale.
function2
:
source
docs
Bases: heatmap
Heatmap representing the image of a 2d function over a square.
Inputs:
- F : float[batch, 2] -> number[batch]. The (vectorised) function to plot. The input should be a batch of (x, y) vectors. The output should be a batch of scalars f(x, y).
- xrange : (number, number). Lower and upper bounds on the x values to pass into the function.
- yrange : (number, number). Lower and upper bounds on the y values to pass into the function.
- width : int. The number of character columns in the plot. This will also become the number of grid squares along the x axis.
- height : int. The number of character rows in the plot. This will also be half of the number of grid squares, since the result is an image plot with two half-character-pixels per row.
- vrange : optional (number, number). Expected lower and upper bounds on the f(x, y) values. Used for determining the bounds of the colour scale. By default, the minimum and maximum output over the grid are used. Values outside these bounds saturate at the nearest end of the colour scale.
- colormap : optional colormap (e.g. mp.viridis). By default, the output will be in greyscale, with black corresponding to vrange[0] and white corresponding to vrange[1]. You can choose a different colormap (e.g. mp.reds, mp.viridis, etc.) here.
-
endpoints : bool (default: False). By default, the grid squares tile the ranges exactly and each one shows the value of the function at its own centre.
If true, the function is instead sampled at points spread from one end of each range to the other, so that the four corner squares show the four corner combinations of xrange and yrange. The squares then reach half a square beyond the ranges, which the axes still report as the limits.
vfunction2
:
source
docs
Bases: image
Colour field representing a 2d vector field over a rectangle.
Every pixel is coloured by the vector the function returns there: the direction becomes the hue and the magnitude becomes the brightness. Unlike a field of arrows this shows a vector at every pixel, so the structure of the field---its sources, sinks, saddles and the channels between them---is visible at whatever resolution the terminal allows.
Inputs:
- F : float[batch, 2] -> float[batch, 2]. The (vectorised) field to plot. The input is a batch of (x, y) positions. The output should be the batch of (u, v) vectors at those positions.
- xrange : (number, number). Lower and upper bounds on the x values to pass into the function.
- yrange : (number, number). Lower and upper bounds on the y values to pass into the function.
- width : int. The number of character columns in the plot. This will also become the number of grid squares along the x axis.
- height : int. The number of character rows in the plot. This will also be half of the number of grid squares, since the result is an image plot with two half-character-pixels per row.
-
vrange : optional (number, number). Expected lower and upper bounds on the magnitude of the vectors, used to scale them into the unit disc for the colormap. By default the lower bound is zero and the upper bound is the largest magnitude over the grid, so that the fastest part of the field is at full brightness. Magnitudes outside these bounds saturate at the nearest end.
The lower bound is zero by default rather than the smallest magnitude, because a vector field's zeros are where its structure is, and they should come out black. * colormap : optional vector colormap (e.g. mp.chroma). Applied to the scaled field. Defaults to
mp.chroma. A custom colormap receives the scaledfloat[h, w, 2]field and must return an RGB image of shape[h, w, 3]. * endpoints : bool (default: False). By default, the grid squares tile the ranges exactly and each one shows the value of the field at its own centre.If true, the field is instead sampled at points spread from one end of each range to the other, so that the four corner squares show the four corner combinations of xrange and yrange. The squares then reach half a square beyond the ranges, which the axes still report as the limits.
cfunction2
:
source
docs
Bases: image
Domain colouring of a complex function over a rectangle of the plane.
Every pixel is coloured by the value the function takes there: the phase becomes the hue and the modulus becomes the lightness, so a zero of the function shows up as a black point, a pole as a white one, and the order of either can be counted off the number of times the colour wheel turns around it.
Inputs:
- F : complex[batch] -> complex[batch]. The (vectorised) function to plot. The input is a batch of points of the complex plane. The output should be the batch of values there.
- xrange : (number, number). Lower and upper bounds on the real part of the input.
- yrange : (number, number). Lower and upper bounds on the imaginary part of the input.
- width : int. The number of character columns in the plot. This will also become the number of grid squares along the real axis.
- height : int. The number of character rows in the plot. This will also be half of the number of grid squares, since the result is an image plot with two half-character-pixels per row.
- colormap : optional vector colormap (e.g. mp.domain).
Applied to the values. Defaults to
mp.domain. There is no range to configure, because a domain colouring puts the modulus on an absolute scale---the colormap owns it. A custom colormap receives thecomplex[h, w]values and must return an RGB image of shape[h, w, 3]. -
endpoints : bool (default: False). By default, the grid squares tile the ranges exactly and each one shows the value of the function at its own centre.
If true, the function is instead sampled at points spread from one end of each range to the other, so that the four corner squares show the four corner combinations of xrange and yrange. The squares then reach half a square beyond the ranges, which the axes still report as the limits.
Sampling the function at the centre of each square is the default here for
a further reason: a function with a pole at a round number, such as 1/z
at the origin, is then never evaluated exactly on it.
histogram2
:
source
docs
Bases: heatmap
Heatmap representing the density of a collection of 2d points.
Inputs:
- x : number[n]. X coordinates of 2d points to bin and count.
- y : number[n]. Y coordinates of 2d points to bin and count.
- width : int (default 24). Specifies the width of the plot in characters. This is also the number of bins in the x direction.
- height : int (default 12). Specifies the height of the plot in characters. This is also half the number of bins in the y direction.
- xrange : optional (number, number).
The x-axis limits
(xmin, xmax). If not provided, the limits are inferred from the min and max x-values in the data. - yrange : optional (number, number).
The y-axis limits
(ymin, ymax). If not provided, the limits are inferred from the min and max y-values in the data. - weights : optional number[n]. If provided, each 2d point in data contributes this amount to the count for its bin (rather than the default 1). See np.histogram2d's weights argument for details.
- density : bool (default False). If true, normalise bin counts so that they sum to 1,0. See np.histogram2d's density argument for details.
- max_count : optional number. If provided, cell colours are scaled so that only bars matching or exceeding this count max out the colour. Otherwise, the colours are scaled so that the bin with the highest count has the colour maxed out. An explicitly supplied value must be positive. If every bin has a count of zero, all cells remain at the bottom of the colour scale.
- colormap : optional colormap (e.g. mp.viridis). By default, the output will be in greyscale, with black corresponding to zero density and white corresponding to max_count. You can choose a different colormap (e.g. mp.reds, mp.viridis, etc.) here.
progress
:
source
docs
Bases: plot
A single-line progress bar.
Construct a progress bar with a percentage label. The bar is rendered using Unicode block element characters to show fractional progress with finer granularity.
Inputs:
- progress : float. The progress to display, as a float between 0.0 and 1.0. Values outside this range will be clipped.
- width : int (default: 40). The total width of the progress bar plot in character columns, including the label and brackets.
- height: int (default: 1). The height of the progress bar in character rows.
- color : optional ColorLike. The color of the filled portion of the progress bar. Defaults to the terminal's default foreground color.
bars
:
source
docs
Bases: plot
A multi-line bar chart.
Transform a list of values into horizontal bars with width indicating the values. The bars are rendered using Unicode block element characters for finer granularity.
Inputs:
- values : float[n]. An array of non-negative values to display.
- width : int (default: 30). The total width of full bars.
- bar_height: int (default: 1). The number of rows comprising each bar.
- bar_spacing: int (default: 0). The number of rows between each bar.
- vrange : optional (number, number). The interval of values the bars measure: a bar at the first value or below has zero width and one at the second value or above occupies the whole width. By default the interval runs from zero to the largest value, so that the largest bar or bars fill the width. Measuring from zero rather than from the smallest value is what makes a bar's width readable on its own, and a chart of equal values a row of full bars.
- color : optional ColorLike. The color of the filled portion of the bars. Defaults to the terminal's default foreground color.
- colors : optional ColorLike[n].
The colours of the filled portion of each bar. Should be an array or
list of the same length as
values.
A value that is not a number is left out of an inferred interval, and its bar has zero width.
TODO:
- Make it possible to draw bars to the left for values below 0.
- Make it possible to align all bars to the right rather than left.
histogram
:
source
docs
Bases: bars
A histogram bar chart.
Transform a sequence of values into horizontal bars representing the density in different bins. The bars are rendered using Unicode block element characters for finer granularity.
Inputs:
- data : number[n]. An array of values to count.
- xrange : optional (number, number). If provided, bins range over this interval, and values outside the range are discarded. Same as np.histogram's range argument.
- bins : int (default: 10). Used to determine number of bins. Bins are evenly spaced as if this number if provided to np.histogram's bins argument.
- weights : optional number[n]. If provided, each element in data contributes this amount to the count for its bin (rather than the default 1). See np.histogram's weights argument for details.
- density : bool (default False). If true, normalise bin counts so that they sum to 1,0. See np.histogram's density argument for details.
- max_count : optional number. If provided, the bars are scaled so that only bars matching or exceeding this count are full. Otherwise, the bars are scaled so that the bin with the highest count has a full bar.
- width : int (default: 22). The total width of full bars.
- color : optional ColorLike. The color of the filled portion of the bars. Defaults to the terminal's default foreground color.
columns
:
source
docs
Bases: plot
A column chart.
Transform a list of values into vertical columns with height indicating the values. The columns are rendered using Unicode block element characters for finer granularity.
Inputs:
- values : number[n]. An array of non-negative values to display.
- height : int (default: 10). The total width of full columns.
- column_width: int (default 1).
- column_spacing: int (default 0).
- vrange : optional (number, number). The interval of values the columns measure: a column at the first value or below has zero height and one at the second value or above occupies the whole height. By default the interval runs from zero to the largest value, so that the tallest column or columns fill the height. Measuring from zero rather than from the smallest value is what makes a column's height readable on its own, and a chart of equal values a row of full columns.
- color : optional ColorLike. The color of the filled portion of the columns. Defaults to the terminal's default foreground color.
- colors : optional ColorLike[n].
The colours of the filled portion of each column. Should be an array or
list of the same length as
values.
A value that is not a number is left out of an inferred interval, and its column has zero height.
TODO:
- Make it possible to draw columns downward for values below 0.
- Make it possible to align all columns to the top rather than bottom.
vistogram
:
source
docs
Bases: columns
A histogram column chart ("vertical histogram", referring to the direction of the bars rather than the bins).
Transform a sequence of values into columns representing the density in different bins. The columns are rendered using Unicode block element characters for finer granularity.
Inputs:
- data : number[n]. An array of values to count.
- xrange : optional (number, number). If provided, bins range over this interval, and values outside the range are discarded. Same as np.histogram's range argument.
- bins : int (default: 10). Used to determine number of bins. Bins are evenly spaced as if this number if provided to np.histogram's bins argument.
- weights : optional number[n]. If provided, each element in data contributes this amount to the count for its bin (rather than the default 1). See np.histogram's weights argument for details.
- density : bool (default False). If true, normalise bin counts so that they sum to 1,0. See np.histogram's density argument for details.
- max_count : optional number. If provided, the bars are scaled so that only bars matching or exceeding this count are full. Otherwise, the bars are scaled so that the bin with the highest count has a full bar.
- height : int (default: 22). The total height of full bars.
- color : optional ColorLike. The color of the filled portion of the bars. Defaults to the terminal's default foreground color.
candles
:
source
docs
Bases: plot
A candlestick chart.
Draw one candle per period, each a filled body spanning the opening and closing values with a thin wick reaching out of it to the high and the low. The body is colored by whether the period closed above or below where it opened.
Inputs:
- opens, highs, lows, closes : number[n]. The four values of each period. Each high must be at least as large as the opening and closing values of its period, and each low at most as small, as the wick reaches out of the body rather than into it. Every value must be a number: a period one of whose four is unknown has no candle to draw.
- length : int (default: 12). The number of character cells along the value axis.
- body_thickness : int (default 1). The number of cells across each body. The wick runs along the middle one, so an even thickness leaves it off centre.
- spacing : int (default 0). The number of blank cells between one candle and the next.
- candle_direction : Orientation (default: "vertical"). Which way one candle lies. Vertical candles stand up and march across the screen, which is the way a price series is usually read and so the default; horizontal candles lie flat and stack up it.
- vrange : optional (number, number). The values at the ends of the value axis. By default, the lowest low and the highest high, so that every candle fits. Given a narrower interval, the candles outside it are clipped to it.
- rising : ColorLike (default: a green). The color of a candle that closed at or above its opening value.
- falling : ColorLike (default: a red). The color of a candle that closed below its opening value.
- wick : optional ColorLike. The color of the wicks. By default each wick takes the color of the body it belongs to.
- background : ColorLike (default: a near-black). The color behind the candles. Unlike most plots, a candlestick chart paints its whole rectangle rather than leaving the terminal's background showing: a body is positioned to an eighth of a character cell, and reaching every eighth means drawing some bodies as a background-colored block over a body-colored cell, which needs the background named.
- style : LineStyle (default: LineStyle.LIGHT). The weight of the wicks.
The plot carries its value range on the axis its candles stand along and no
coordinate on the other, since the candles are a sequence of periods rather
than a measured axis. So axes labels its value axis and leaves the other
three sides alone.
A body is positioned to the nearest eighth of a character cell and a wick to the nearest half. A body always keeps its true length, and a candle that opened and closed at the same value still shows a hairline.
A candle and a box are one mark with different switches thrown, so this is
boxes with its caps, its median and its outlying points switched off, and
the two share their drawing. See the box-plots note.
boxes
:
source
docs
Bases: plot
A box plot, one box per group of samples.
Draw one box per group, spanning the first and third quartiles, divided at the median, with whiskers reaching out to the extremes of the group and any sample beyond them drawn as an individual point.
Inputs:
- data : sequence of number[k]. The samples in each group. The groups need not be the same length. A 2d array works, one group per row. A sample that is not finite is a measurement that was not made: it is left out of the summary rather than shifting the quartiles or counting as a point beyond the whiskers, and a group with no finite samples at all is an error.
- length : int (default: 30). The number of character cells along the value axis.
- box_thickness : int (default: 3). The number of character cells across one box. At least 3 for an outlined box, which needs two edges and an interior between them, and at least 1 for a filled one.
- box_spacing : int (default: 1). The number of blank cells between one box and the next.
- box_direction : Orientation (default: "horizontal"). Which way one box lies. Horizontal boxes lie flat and stack up the screen; vertical boxes stand up and march across it. Horizontal is the default because it gives the value axis both more cells and finer ones: terminals are wider than they are tall, and character cells are taller than they are wide.
- filled : bool (default: False). Whether to draw each box as a solid fill rather than an outline. A fill reaches the nearest eighth of a cell where an outline is confined to whole cells, at the cost of needing a background color.
- caps : bool (default: True). Whether to draw a cap across the end of each whisker.
- median : bool (default: True). Whether to divide each box at its median. The mark is dropped from a box with no room for it regardless.
- whisker_iqrs : optional number (default: 1.5). How far the whiskers reach, as a multiple of the interquartile range beyond the quartiles. Each whisker stops at the furthest sample within that reach, and every sample beyond it is drawn as a point: the default is Tukey's rule. Given None, the whiskers reach the smallest and largest samples instead and no points are drawn.
- vrange : optional (number, number). The values at the ends of the value axis. By default, the smallest and largest samples, so that every group fits. Given a narrower interval, the boxes outside it are clipped to it and the points outside it are dropped.
- color : optional ColorLike. The color of every box. Defaults to the terminal's foreground color, or to white for a filled box, whose color has to be named for the negatives to be drawn against it.
- colors : optional ColorLike[n].
The color of each box. Should be a list or array as long as
data. - background : optional ColorLike. The color behind the boxes. A filled plot paints its whole rectangle, defaulting to a near-black, because a fill reaches every eighth of a cell only by drawing some eighths as negatives, which needs the background named. An outlined plot leaves the terminal's own background showing unless one is given.
- style : LineStyle (default: LineStyle.LIGHT). The weight of the whiskers, the caps and an outlined box's outline.
- median_style : optional LineStyle.
The weight of a filled box's median. Defaults to light lying flat and
heavy standing up, each being the one that matches the eighth blocks
the median lands on at the edges of a cell. An outlined box's median
joins its outline and so takes
styleinstead.
The plot carries its value range on one axis and no coordinate on the
other, since the groups are a list of categories rather than a measured
axis. So axes labels the value axis and leaves the other three sides
alone.
hilbert
:
source
docs
Bases: plot
Visualize a 1D boolean array along a 2D Hilbert curve.
Maps a 1D sequence of data points to a 2D grid using a space-filling Hilbert curve, which helps preserve locality. The curve is rendered using braille unicode characters for increased resolution.
Inputs:
- data : bool[N].
A 1D array of booleans. The length
Ndetermines the order of the Hilbert curve required to fit all points. True values are rendered as dots, and False values are rendered as blank spaces. - color : optional ColorLike.
The foreground color used for dots (points along the curve where
dataisTrue). Defaults to the terminal's default foreground color.
calendar
:
source
docs
Bases: plot
Calendar heatmap of values observed on dates.
Draws a block per month, a row per week and a column per weekday, colouring each day by its value, and wraps the months into a grid. A year of daily data becomes a wall calendar.
Inputs:
- data : DateSeries.
The dated values to colour: a mapping from dates to values, a pair of
sequences of dates and values, or one date and the values on the days
running from it. See
DateSeriesfor the full list of forms. - vrange : optional (number, number). The interval of values the colormap covers: values at the first limit or below come out at the bottom of the colormap and values at the second or above come out at the top. By default the interval runs from the lowest to the highest value among the days drawn, so that the colours span the data.
- colormap : optional ColorMap. Maps each day's value, normalised to the range 0.0 to 1.0, onto its colour. By default the days are shades of grey, black for the bottom of the range and white for the top.
- daterange : optional (date, date).
The first and last day to draw, each spelled any way a
DateLikecan be. Days outside the range are left blank even where the data has values for them. If omitted, the range spans the dates in the data. - cols : optional int (default 4). The number of months in each row of the grid. If None, as many as fit the width of the terminal.
- first_weekday : int (default 0).
The weekday to start each week on, from 0 for Monday to 6 for Sunday,
numbered as in Python's
calendarmodule. - day_width : int (default 2). The number of character cells each day is drawn in. Two is close to square in a terminal.
- month_spacing : int (default 1).
The gap to leave between month blocks, counted in days so that it stays
square whatever
day_widthis. - month_labels : bool (default True). Whether to caption each month with its name and year, abbreviating the caption to fit if the days are narrow.
- weekday_labels : bool (default True). Whether to head each month's columns with the initials of the weekdays.
- bgcolor : optional ColorLike. The color to show through the notch in the corner of each day. Defaults to a transparent background, showing the terminal's own.
A date the data says nothing about, or gives a value that is not finite, is left blank, so that a day with no value stays distinct from a day whose value is zero.
weeks
:
source
docs
Bases: plot
Calendar heatmap of values observed on dates, as an unbroken strip.
Draws a column per week and a row per weekday, colouring each day by its value, running without a break from the first day drawn to the last. A year of daily data becomes a band seven rows deep, captioned with the months along the top.
Inputs:
- data : DateSeries.
The dated values to colour: a mapping from dates to values, a pair of
sequences of dates and values, or one date and the values on the days
running from it. See
DateSeriesfor the full list of forms. - vrange : optional (number, number). The interval of values the colormap covers: values at the first limit or below come out at the bottom of the colormap and values at the second or above come out at the top. By default the interval runs from the lowest to the highest value among the days drawn, so that the colours span the data.
- colormap : optional ColorMap. Maps each day's value, normalised to the range 0.0 to 1.0, onto its colour. By default the days are shades of grey, black for the bottom of the range and white for the top.
- daterange : optional (date, date).
The first and last day to draw, each spelled any way a
DateLikecan be. Days outside the range are left blank even where the data has values for them. If omitted, the range spans the dates in the data. - width : optional int. The most characters the strip may occupy. A strip with more weeks than fit continues on further bands below, each captioned again, with a blank row between them. If omitted the strip runs its whole length on one band, however wide that is.
- first_weekday : int (default 0).
The weekday to put in the top row, from 0 for Monday to 6 for Sunday,
numbered as in Python's
calendarmodule. - day_width : int (default 2). The number of character cells each day is drawn in. Two is close to square in a terminal.
- year_labels : bool (default True). Whether to caption the first month drawn of each year with the year, in a row above the months.
- month_labels : bool (default True). Whether to caption the week each month begins in with the month's abbreviated name. A caption that would collide with the one before it is dropped, so narrow days give fewer of them.
- weekday_labels : bool (default True). Whether to head each row with the initial of its weekday, in a gutter two characters wide to the left of the strip.
- bgcolor : optional ColorLike. The color to show through the notch in the corner of each day. Defaults to a transparent background, showing the terminal's own.
A date the data says nothing about, or gives a value that is not finite, is left blank, so that a day with no value stays distinct from a day whose value is zero.
Rule = Literal['skip', 'blank', 'single', 'double']
:
source
docs
What is drawn along one of a table's rules, in increasing order of what it
costs and what it shows.
"skip": nothing at all, taking no row or column."blank": a row or column of space, which any rule crossing it still runs through."single": a light line."double": a double line.
table
:
source
docs
Bases: plot
A grid of values, formatted into aligned columns and ruled.
Inputs:
- data : list of dicts | dict of lists | 2d array.
The values to tabulate, in any of three spellings:
- A sequence of mappings, one per row. The columns are the keys, in the order they are first seen, and a row missing one of them leaves that cell blank.
- A mapping from column to the values down it. A column shorter than the longest is blank where it runs out.
- A sequence of sequences, or a 2d array, one row of values each. These name no columns of their own.
- headers : optional list of str, or dict. The columns to show. Where the data names its columns, a list picks them out and orders them, and a mapping from key to name does that and renames them as well. Where the data names none, a list names them, and without one the table has no header row.
- index : optional list of str. Labels for the rows, drawn in a column of their own before the first. The columns everything else is specified per-column for do not count this one.
- index_name : str (default: ""). The header over the index column.
-
formats : optional str | callable | list | dict. How to turn a value into the text of its cell. One of:
- A format spec, as
formattakes, like".3f". - A template with a field in it, as
str.formattakes, like"{:.1%}". - A function from a value to a string.
- A list of any of those, one per column, or None to leave a column formatted as it would be by default.
- A mapping from a column's header to any of those.
By default a float is shown to four significant figures, and anything else as
strshows it. A value of None is blank whatever the format. * aligns : optional Align | list | dict. Where to put a value in its cell. One for the whole table, a list with one per column, or a mapping from a column's header. By default a column holding nothing but numbers is aligned right, so that its digits line up, and every other column left. A header follows its column. * toprule : optional Rule. The rule above the header,"single"by default. * midrule : optional Rule. The rule between the header and the body,"double"by default. Only a table with a header row has one. * rowrule : optional Rule. The rule between one body row and the next,"skip"by default. * bottomrule : optional Rule. The rule below the body,"single"by default. * leftrule : optional Rule. The rule down the left of the table,"skip"by default. * indexrule : optional Rule. The rule between the index column and the body,"skip"by default. Only a table with an index has one. * colrule : optional Rule. The rule between one column and the next,"skip"by default. * rightrule : optional Rule. The rule down the right of the table,"skip"by default. * max_col_width : optional int. The widest a column of text may be. Anything longer is cut, with an ellipsis marking what was taken off. By default a column is as wide as the longest thing in it. * cell_padding : int (default: 1). Columns of space between a value and the rule on each side of it. Two neighbouring cells give twice this much space between columns that have no rule between them. An outer edge with no rule on it is not padded, so that the table starts flush with its first column. * color : optional ColorLike. The color of everything in the table that is not given a color of its own. Defaults to the terminal's default foreground color. * bgcolor : optional ColorLike. The color behind the whole table. Defaults to a transparent background. * header_color : optional ColorLike. The color of the header row and the index column. Defaults tocolor. * rule_color : optional ColorLike. The color of the rules. Defaults tocolor. * colors : optional ColorLike[nrows, ncols]. The color of the text in each body cell, not counting the header row or the index column. * bgcolors : optional ColorLike[nrows, ncols]. The color behind each body cell. Together with a colormap this shades a table by its values, so that it reads as a heatmap that can still be read off exactly. * colormap : optional ColorMap. Applied tocolorsandbgcolorsbefore either is read as colors, so that they can be given as the data the table is showing. - A format spec, as
A cell whose text has newlines in it takes as many lines as it needs, and every other cell in its row grows to match.
text
:
source
docs
Bases: plot
A plot object containing one or more lines of text.
This class wraps a string in the plot interface, allowing it to be composed with other plot objects. It handles multi-line strings by splitting them at newline characters.
Inputs:
- text : str. The text to be displayed. Newline characters will create separate lines in the plot.
- height : int (default: 0). The least number of rows the plot takes. More are taken if the text has more lines than this.
- width : int (default: 0). The least number of columns the plot takes. More are taken if a line is longer than this.
- align : Align (default: "left"). Where each line sits in the width. Only has room to act where a width is given that is wider than the longest line.
- fgcolor : optional ColorLike. The foreground color of the text. Defaults to the terminal's default foreground color.
- bgcolor : optional ColorLike. The background color for the text, the rows and columns no line reaches included. Defaults to a transparent background.
Carriage returns and newlines separate lines. Other C0 and C1 control characters are rejected, including the escapes used for raw ANSI formatting: styling has to be part of the plot so that composition and rendering know its size.
The empty string has no lines in it, and so is a plot of no rows, which
stacks and composes as nothing. A single empty line is "\n".
TODO:
- Account for non-printable and wide characters.
border
:
source
docs
Bases: plot
Add a border around a plot using box-drawing characters.
Inputs:
- plot : plot. The plot object to be enclosed by the border.
- title: str. An optional title for the box. Placed centrally along the top row of the box. Truncated to fit.
- style : BoxStyle (default: BoxStyle.ROUND).
The style of the border. Predefined styles are available in
BoxStyle. - color : optional ColorLike. The color of the border characters. Defaults to the terminal's default foreground color.
Side = Literal['crop', 'pad', 'rule', 'label']
:
source
docs
What is drawn along one side of an axes, in increasing order of what it
costs and what it shows.
"crop": nothing at all, taking no space."pad": one blank cell, holding the space open."rule": one cell, holding a line."label": the line, ticks at its two ends, and a row or column outside it carrying the limits of the coordinate and the name of the axis.
axes
:
source
docs
Bases: plot
Rule and label the sides of a plot that carries coordinates.
Each of the four sides is drawn independently, so that a plot can be given a full frame with labels below and to its left, a single labelled rule along one side, or anything in between. The characters where the rules meet, and the ticks that reach out towards the labels, follow from which sides are drawn.
Inputs:
- plot : plot. The plot to draw the axes around. Must carry a window.
-
north, east, south, west : optional Side. What to draw along each side:
"crop","pad","rule"or"label". A side may only be labelled if the plot carries the matching coordinate: north and south need an x range, east and west a y range.Left unspecified, each axis the plot carries is labelled once---below it and to its left---and the remaining sides are ruled if the plot carries both coordinates, or dropped if it carries only one, so that a colorbar is labelled along one side and left alone on the others. Asking for a label on one side of an axis rules the opposite side rather than labelling it twice. * title: optional str. Placed centrally along the top. Written into the north side if that side is blank or ruled, and given a row of its own above everything otherwise. Truncated to fit. * xlabel: optional str. The name of the x axis, written along each labelled horizontal side, between the limits and truncated to fit between them. * ylabel: optional str. The name of the y axis, written vertically along each labelled vertical side. Truncated to fit. * xfmt: str (default "{x:.1f}"). Format string for x labels. Should have one keyword argument with the key 'x'. * yfmt: str (default "{y:.1f}"). Format string for y labels. Should have one keyword argument with the key 'y'. * ypad: int (default 1). How many columns between a vertical axis and its name. * style : LineStyle (default: LineStyle.LIGHT). The weight of the rules. * color : optional ColorLike. The color of the rules and the labels. Defaults to 50% gray. Set to
Noneto use the foreground color.
A limit that will not fit in the space its side has is replaced by hashes, as a spreadsheet does, rather than shortened into a different number or allowed to widen the plot.
Direction = Literal['up', 'down', 'left', 'right']
:
source
docs
Which way along the screen a colorbar runs: the axis it lies along, and the
end of that axis its interval finishes at.
"up","down": a vertical bar, two pixels per cell."left","right": a horizontal bar, one pixel per cell.
colorbar
:
source
docs
Bases: heatmap
A gradient standing for the mapping from values onto colours.
The bar is a strip one coordinate wide, so axes labels the one side that
means anything and leaves the other three alone, and a border boxes it
without claiming it has two dimensions.
Inputs:
-
source : plot | (number, number). The interval the bar covers. Any plot that kept one lends it---a
heatmapand everything built on one, acalendar, aweeks, abars---so that the numbers on the bar cannot drift from the numbers in the picture. An interval on its own works too, for a scale assembled by hand.A plot whose values are all the same settled on an interval covering nothing, which is one colour and no axis to label it along, so there is no bar to draw for it and it is refused. * colormap : optional ColorMap. Maps each position along the bar onto its colour. By default the bar runs black to white.
Name the same one the picture was drawn with: the bar is not told what the picture used, in the same way that nothing else in this library infers a colormap. A bar is a gradient, so a continuous colormap is what it can stand for; a palette wants a swatch beside each label, which is a different plot and is not built. * direction : Direction (default: "up"). Which way along the screen the values increase, naming both the axis the bar runs along and the sense it runs in. The first limit of the interval sits at the end the direction points away from, and the second at the end it points towards. * length : int (default: 12). How many character cells the bar covers along the scale. * thickness : int (default: 1). How many character cells the bar covers across the scale.
A vertical bar has twice the gradient resolution of a horizontal one of the same length, since a character cell holds two half-block pixels vertically and one horizontally.
heat = mp.heatmap(values, colormap=mp.viridis)
mp.axes(heat, title="field") + mp.axes(mp.colorbar(heat, colormap=mp.viridis), east="label")
blank
:
source
docs
Bases: plot
Creates a rectangular plot composed entirely of blank space.
Useful for adding padding or aligning items in a complex layout.
Inputs:
- height : optional int. The height of the blank area in character rows. Default 1.
- width : optional int. The width of the blank area in character columns. Default 1.
hstack
:
source
docs
Bases: plot
Horizontally arrange one or more plots side-by-side.
If the plots have different heights, the shorter plots will be padded with blank space at the bottom to match the height of the tallest plot.
Inputs:
- *plots : plot. A sequence of plot objects to be horizontally stacked.
vstack
:
source
docs
Bases: plot
Vertically arrange one or more plots, one above the other.
If the plots have different widths, the narrower plots will be padded with blank space on the right to match the width of the widest plot.
Inputs:
- *plots : plot. A sequence of plot objects to be vertically stacked.
dstack
:
source
docs
Bases: plot
Overlay one or more plots on top of each other.
The plots are layered in the order they are given, with later plots in the sequence drawn on top of earlier ones. The final size of the plot is determined by the maximum width and height among all input plots. Non-blank characters from upper layers will obscure characters from lower layers.
Inputs:
- *plots : plot. A sequence of plot objects to be overlaid.
dstack2
:
source
docs
Bases: dstack
Overlay one or more plots on top of each other.
The plots are layered in the order they are given, with later plots in the sequence drawn on top of earlier ones. The final size of the plot is determined by the maximum width and height among all input plots. Non-blank characters from upper layers will obscure characters from lower layers.
Unlike dstack, every plot must carry a coordinate on both axes, and they must all share one window: the same intervals covered in the same number of character cells. Two plots covering the same intervals in different numbers of cells put the same coordinate in different places, and a rendered plot cannot be resampled to fix that, so it is refused.
Inputs:
- *plots : plot. A sequence of plot objects to be overlaid. At least one, all sharing one window.
wrap
:
source
docs
Bases: plot
Arrange a sequence of plots into a grid.
The plots are arranged from left to right, wrapping to a new line when the specified number of columns is reached. All cells in the grid are padded to the size of the largest plot in the sequence.
Inputs:
- *plots : plot. A sequence of plot objects to be arranged in a grid.
- cols : optional int. The number of columns in the grid. If not provided, it is automatically determined based on the terminal width and the width of the largest plot.
- transpose: optional bool (default False). If False (default), the plots are arranged in reading order, from left to right and then from top to bottom. If True, the plots are arranged in column order, from top to bottom and then from left to right.
center
:
source
docs
Bases: plot
Pad a plot with blank space to center it within a larger area.
If the specified height or width is smaller than the plot's dimensions,
the larger dimension is used, effectively preventing the plot from being
cropped.
Inputs:
- plot : plot. The plot object to be centered.
- height : optional int. The target height of the new padded plot. If not provided, it defaults to the original plot's height (no vertical padding).
- width : optional int. The target width of the new padded plot. If not provided, it defaults to the original plot's width (no horizontal padding).