matthewplotlib.plots
A collection of building blots 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:
scatterfunctionscatter3imagefunction2histogram2progressbarshistogramcolumnsvistogramhilbert
Furnishing plots:
Arrangement plots:
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.
Convert the plot into a string for printing to the terminal.
Note: plot.renderstr() is equivalent to str(plot).
Convert the plot into a string that, if printed immediately after plot.renderstr(), will clear that plot from the terminal.
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.
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.
TODO:
- Maybe allow configurable xyz ranges with clipping prior to projection?
- Make sure this is not a subclass of scatter for the purposes of labelling axes as that would use projected coordinates.
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. 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]. If no colormap is provided, values are treated as greyscale (uniform colorisation). If a continuous colormap is provided, values are mapped to RGB values.int[h,w]: A 2D array of ints. If no colormap is provided, values should be in the range [0,255], they are treated as greyscale (uniform colorisation). If a discrete colormap is provided, values should be in range as indices for the colormap, they will be mapped to RGB triples as such.
colormap : optional ColorMap. Function mapping (batches of) scalars to (batches of) RGB triples. Examples are provided by this library, such as:
- continuous colormaps like
viridis : float[...] -> uint8[...,3], and - discrete colormaps like
pico8 : int[...] -> uint8[...,3]. Ifimhas no RGB dimension, it is transformed to a grid of RGB triples using one of these colormaps.
- continuous colormaps like
TODO:
- Offer normalisation?
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 : (float, float). Lower and upper bounds on the x values to pass into the function.
- yrange : (float, float). 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.
- zrange : optional (float, float). 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.
- colormap : optional colormap (e.g. mp.viridis). By default, the output will be in greyscale, with black corresponding to zrange[0] and white corresponding to zrange[1]. You can choose a different colormap (e.g. mp.reds, mp.viridis, etc.) here.
endpoints : bool (default: False). If true, endpoints are included from the linspaced inputs, and so the grid elements in each corner will represent the different combinations of xrange/yrange.
If false (default), the endpoints are excluded, so the lower bounds are met but the upper bounds are not, meaning each grid square color shows the value of the function precisely at its lower left corner.
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.
- 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.
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.
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 : None | float | (float, float).
Determine the scaling of the bars.
- If omitted, the bars are scaled such that the bar(s) with the largest value occupy the whole width.
- If a single number, then the bars are scaled so that bars with that value (or greater) would occupy the whole width.
- If a pair of numbers, the bars are scaled so that bars with the first value (or less) would have zero width and bars with the second value (or greater) would occupy the whole width.
- 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.
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.
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 (float, float). 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.
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 : None | number | (number, number).
Determine the scaling of the columns.
- If omitted, the columns are scaled such that the columns(s) with the largest value occupy the whole width.
- If a single number, then the columns are scaled so that columns with that value (or greater) would occupy the whole width.
- If a pair of numbers, the columns are scaled so that columns with the first value (or less) would have zero width and columns with the second value (or greater) would occupy the whole width.
- 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.
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.
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 (float, float). 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.
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.
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.
- color : 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. Defaults to a transparent background.
TODO:
- Allow alignment and resizing.
- Account for non-printable and wide characters.
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.
Add an annotated border around a 2d plot using box-drawing characters.
Inputs:
- plot : scatter | function2 | histogram2 | dstack2. The plot object to be enclosed by the axes. Must have an xrange and a yrange.
- title: optional str. An optional title for the axes. Placed centrally along the top row of the axes. Truncated to fit.
- xlabel: optional str. String to be used as label under the x axis. Truncated to fit between min and max labels.
- ylabel: optional str. String to be used as label next to the y axis. Written vertically, and truncated to fit between min and max labels.
- xfmt: str (default "{x:.2f}"). Format string for x labels. Should have one keyword argument with the key 'x'.
- yfmt: str (default "{y:.2f}"). Format string for y labels. Should have one keyword argument with the key 'y'.
- ypad: int (default 1). How many columns between the y axis and the vertical y axis label.
- 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 and labels. Defaults to 50% gray.
Set to
Noneto use foreground color.
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.
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.
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.
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.
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, the plots must have xrange and range attributes, and these must all match. The allowable types are scatter, function2, histogram2, and dstack2.
Inputs:
- *plots : scatter | function2 | histogram2 | dstack2. A sequence of plot objects to be overlaid. Must have matching xrange and yrange.
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.
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).
Supply a list of plots and a filename and this method will create an animated gif.
Inputs:
- plots : list[plot]. The list of plots forming the frames of the animation.
- filename : str. Where to save the gif. Should usually include a '.gif' extension.
- upscale : int (>=1, default is 1).
Represent each pixel with a square of side-length
upscalepixels. - downscale : int (>=1, default is 1).
Keep every
downscaleth pixel. Does not need to evenly divide the image height or width (think slice(0, height or width, downscale)). Applied after upscaling. - bgcolor : ColorLike | None. Default background colour. If none, a transparent background is used.
- fps : int. Approximate frames per second encoded into the gif.
- repeat : bool (default True). If true (default), the gif loops indefinitely. If false, the gif only plays once.
Notes:
- All plots should be the same size. If they are not, they will be aligned at the top left corner (padded with transparent pixels on the bottom and right). If you want different padding, add blank blocks before passing to this function.
TODO:
- Consider making this a plot aggregator and overriding .saveimg(). The only problem is that it's unclear what to use for renderimg and renderstr.
- Duration is currently broken, seems to be due to Image internally doing a format conversion from RGBA -> P while saving the gif. Should convert beforehand?