plotille

repository·master·Indexed 19 days ago

https://github.com/tammoippen/plotille

A zero-dependency Python library for creating terminal-based plots, scatter plots, histograms, and heatmaps using braille dots and foreground/background colors. It provides a high-level Figure class for composing complex plots and a low-level Canvas class for direct manipulation of a character-based grid, including support for rendering grayscale images via braille dots or RGB images via background colors.

Tokens
7.3K
Snippets
37
Records
43
Agent score
68%

What's inside plotille

  1. How the `Canvas` class works

    master

    The Canvas class is the underlying engine for all plotting. It manages a grid of characters where each character can contain up to 2x4 Braille dots.

    Coordinate Systems:

    • Reference System: You plot using arbitrary coordinates defined by xmin, ymin, xmax, and ymax.
    • Discrete System: The canvas internally maps these to a dot-based grid.

    All plotting methods (point, line, rect, text, etc.) use the Reference System.

    import plotille
    
    # Initialize a canvas with a specific reference area
    cv = plotille.Canvas(width=40, height=20, xmin=0, ymin=0, xmax=1, ymax=1)
    
    # Plot using reference coordinates
    cv.rect(0.1, 0.1, 0.6, 0.6)
    print(cv.plot())
  2. How the Figure class works

    master

    The Figure class is the recommended way to compose complex plots. You create a Figure instance, configure its properties (like dimensions, axis limits, and labels), add various plots (lines, scatter, histograms, etc.), and then render the result using show().

    Key properties of a Figure include:

    • width, height: int - Number of characters in X/Y directions.
    • x_limits, y_limits: DataValue - The reference coordinate system limits.
    • color_mode: str - The color mode (see plotille.color()).
    • with_colors: bool - Whether to use colors.
    • background: ColorDefinition - The background color.
    • x_label, y_label: str - Axis labels.
    import plotille
    import numpy as np
    
    X = np.sort(np.random.normal(size=1000))
    
    fig = plotille.Figure()
    fig.width = 60
    fig.height = 30
    fig.set_x_limits(min_=-3, max_=3)
    fig.set_y_limits(min_=-1, max_=1)
    fig.color_mode = 'byte'
    fig.plot([-0.5, 1], [-1, 1], lc=25, label='First line')
    fig.scatter(X, np.sin(X), lc=100, label='sin')
    fig.plot(X, (X+2)**2 , lc=200, label='square')
    print(fig.show(legend=True))
  3. Render images on a `Canvas`

    master

    You can render images on a Canvas using two different methods:

    1. braille_image(): Uses Braille dots to represent pixels. Since one character holds 2x4 dots, a width x height character canvas can represent a width*2 x height*4 pixel image. This is best for grayscale/luminance images.
    2. image(): Uses the background color of the characters to represent pixels. This requires mode='rgb' in the Canvas constructor and provides a 1-to-1 mapping between pixels and characters.
    from PIL import Image
    import plotille as plt
    
    # Method 1: Braille dots (Grayscale)
    img = Image.open("path/to/image").convert('L').resize((80, 80))
    cv_braille = plt.Canvas(40, 20)
    cv_braille.braille_image(img.getdata(), threshold=125)
    print(cv_braille.plot())
    
    # Method 2: Background colors (RGB)
    img_rgb = Image.open("path/to/image").convert('RGB').resize((40, 40))
    cv_rgb = plt.Canvas(40, 40, mode='rgb')
    cv_rgb.image(img_rgb.getdata())
    print(cv_rgb.plot())
  4. Install plotille via pip

    master

    Install the plotille package using pip to enable terminal-based plotting with braille dots and colors.

    pip install plotille
  5. Use the Figure class to compose plots

    master

    The Figure class is the primary interface for composing complex plots in plotille. It manages multiple data layers (plots, histograms, text, spans, and heatmaps), axis generation, and rendering to a text-based canvas.

    Key capabilities include:

    • Composition: Add multiple plots, scatter plots, histograms, and text overlays to a single figure.
    • Customization: Set canvas dimensions (width, height), axis labels (x_label, y_label), and color modes.
    • Axis Control: Toggle axes visibility (with_x_axis, with_y_axis), set limits (set_x_limits, set_y_limits), and manage datetime timezones.
    • Rendering: Generate the final plot as a string using the .show() method.
    from plotille import Figure
    
    fig = Figure()
    fig.width = 100
    fig.height = 30
    fig.x_label = "Time"
    fig.y_label = "Value"
    
    # Add data
    fig.plot([1, 2, 3], [10, 20, 30])
    
    # Render to string
    plot_string = fig.show()
    print(plot_string)
  6. Create a standard histogram with `plotille.histogram()`

    master

    Use plotille.histogram() to create a vertical histogram (bottom-to-up). The X-axis represents the values and the Y-axis represents the frequency/counts.

    import plotille
    import numpy as np
    
    print(plotille.histogram(np.random.normal(size=10000)))
  7. Create a scatter plot with `plotille.scatter()`

    master

    Use plotille.scatter() to create a scatter plot. This is essentially a plot() call with interpolation disabled (interp=None). It plots individual points without connecting them with lines.

    import plotille
    import numpy as np
    
    X = np.linspace(0, 10, 100)
    Y = np.sin(X)
    print(plotille.scatter(X, Y, height=30, width=60))
  8. Canvas API Reference

    master

    The plotille.Canvas class provides the following methods for manual drawing in the reference coordinate system:

    • point(x, y, set_=True, color=None, marker=None): Plots a single point. Use set_=False to remove it.
    • line(x0, y0, x1, y1, set_=True, color=None): Plots a line between two points.
    • rect(xmin, ymin, xmax, ymax, set_=True, color=None): Plots a rectangle defined by its bounding box.
    • text(x, y, text, set_=True, color=None): Places text at coordinates.
    • plot(linesep='\n'): Returns the canvas as a printable string.
  9. Using relative coordinates for canvas elements

    master

    Some Figure methods use relative coordinates on the canvas, meaning all coordinates must be in the range [0, 1].

    Relative Coordinate Functions

    • axvline(x, ymin=0, ymax=1, lc=None): Plots a vertical line at x.
    • axvspan(xmin, xmax, ymin=0, ymax=1, lc=None): Plots a vertical rectangle from (xmin, ymin) to (xmax, ymax).
    • axhline(y, xmin=0, xmax=1, lc=None): Plots a horizontal line at y.
    • axhspan(ymin, ymax, xmin=0, xmax=1, lc=None): Plots a horizontal rectangle from (xmin, ymin) to (xmax, ymax).
  10. Create a histogram with `plotille.hist()`

    master

    Use plotille.hist() to create a horizontal histogram where values are counted from left to right. The X-axis represents the data values and the Y-axis represents the counts.

    import plotille
    import numpy as np
    
    print(plotille.hist(np.random.normal(size=10000)))
  11. Create an aggregated histogram with `plotille.hist_aggregated()`

    master

    Use plotille.hist_aggregated() when you have pre-aggregated data (bins and counts) rather than raw values. This is useful for working with APIs like OpenTelemetry Metrics.

    Note: You must provide n+1 bins for n count values. For example, if you have 11 counts, you need 12 bin limits.

    import plotille
    
    counts = [1945, 0, 0, 0, 0, 0, 10555, 798, 0, 28351, 0]
    # len(bins) must be len(counts) + 1
    bins = [float('-inf'), 10, 50, 100, 200, 300, 500, 800, 1000, 2000, 10000, float('+inf')]
    print(plotille.hist_aggregated(counts, bins))
  12. Plotting functions in Figure

    master

    The Figure class provides several methods to add data to a plot. Most methods accept lc (line color) and label arguments.

    Data Plots

    • plot(X, Y, lc=None, interp='linear', label=None, marker=None): Creates a plot with linear interpolation between points.
    • scatter(X, Y, lc=None, label=None, marker=None): Creates a scatter plot with no interpolation.
    • histogram(X, bins=160, lc=None): Creates a histogram over the provided X values.
    • text(X, Y, texts, lc=None): Prints text at specific X, Y coordinates.
    • imgshow(X, cmap=None): Displays data as an image on a 2D regular raster.