plotext Documentation

repository·master·Indexed 24 days ago

https://github.com/piccolomo/plotext

A Python library for rendering high-quality plots, images, and videos directly within a terminal environment. It supports a wide range of visualizations including scatter, line, bar, histogram, date-time, candlestick charts, error bars, and confusion matrices. The library allows for detailed customization of axes, grid lines, markers (including braille and HD), colors, and themes, and can stream video with audio. It is designed for CLI-based workflows and has no mandatory dependencies.

Tokens
14.2K
Snippets
38
Records
69
Agent score
80%

What's inside plotext

  1. Overview of plotext capabilities

    master

    plotext is a library for plotting data directly in the terminal. It supports a wide range of visualization types and media playback:

    • Main Plots: Scatter, line, bar, histogram, and date-time plots (including candlestick charts).
    • Specialized Plots: Error bars and confusion matrices.
    • Decorators: Adding text, lines, and shapes to existing plots.
    • Media: Plotting images (including GIFs) and streaming video with audio (including YouTube).
    • Utilities: Saving plots as text or colored HTML, coloring strings, and a dedicated command line tool.

    Note: The library has no dependencies except for optional ones required for image and video plotting.

  2. Manage Plot Lifecycle and Canvas

    master

    Common utility methods for managing the plot state:

    • Display: Call show() to render the plot. Use interactive(True) to display the plot dynamically without calling show().
    • Saving: Use savefig(path) to save the plot to a file.
    • Clearing:
      • clear_figure(): Clears figure settings.
      • clear_data(): Clears data.
      • clear_color(): Clears color settings.
      • clear_terminal(): Clears the terminal screen.
  3. How nested subplots work

    master

    Subplots in plotext can be nested, meaning any individual subplot can act as the parent for its own matrix of subplots. This allows for complex, hierarchical layouts.

    To create a nested structure, call subplots() on an existing subplot. For example, to create a 2x2 matrix where the first subplot is itself a 3x4 matrix, you can use: plt.subplots(2, 2).subplot(1, 1).subplots(3, 4)

    Note on batch operations: If you call a method on a subplot that is itself a matrix (a parent of other subplots), that method will be applied to all subplots within that matrix simultaneously. This is useful for applying consistent styling to a group of plots at once.

  4. Configure Plot Appearance and Labels

    master

    Use the following methods to customize your plots:

    • Labels: title(), xlabel(), and ylabel().
    • Markers: Use the marker parameter in plotting functions. High definition options include "hd", "fhd", and "braille".
    • Colors: Use the color parameter for data points, or axes_color(), canvas_color(), and ticks_color() for axes/canvas styling. Use theme() for preset styles.
    • Lines: grid(), horizontal_line(), or vertical_line().
    • Axes: xaxes(), yaxes(), or frame() to add/remove axes. Use xfrequency()/xticks() and yfrequency()/yticks() to change numerical tick spacing.
    • Dimensions: plotsize() to change the default terminal-adaptive size.
  5. Integrate Plotext with Rich

    master

    To use Plotext within a rich layout (for example, in a terminal dashboard), you can create a class that inherits from rich.jupyter.JupyterMixin and implements the __rich_console__ method. This method should use plt.build() to get the plot string and rich.ansi.AnsiDecoder to decode the ANSI escape sequences into a format rich can render (like a rich.console.Group).

    from rich.layout import Layout
    from rich.live import Live
    from rich.ansi import AnsiDecoder
    from rich.console import Group
    from rich.jupyter import JupyterMixin
    from rich.panel import Panel
    from rich.text import Text
    import plotext as plt
    
    def make_plot(width, height, phase = 0, title = ""):
        plt.clf()
        # ... plot configuration ...
        return plt.build()
    
    class plotextMixin(JupyterMixin):
        def __init__(self, phase = 0, title = ""):
            self.decoder = AnsiDecoder()
            self.phase = phase
            self.title = title
    
        def __rich_console__(self, console, options):
            self.width = options.max_width or console.width
            self.height = options.height or console.height
            canvas = make_plot(self.width, self.height, self.phase, self.title)
            self.rich_canvas = Group(*self.decoder.decode(canvas))
            yield self.rich_canvas
    
    # Usage with Live
    layout = Layout()
    # ... setup layout ...
    with Live(layout, refresh_per_second=0.0001) as live:
        # ... update layout with Panel(plotextMixin(...)) ...
        live.refresh()
  6. Install plotext via pip

    master

    You can install plotext using pip. Use the standard installation for basic functionality, or install optional extras for specific features like image plotting, video rendering, or command-line completion.

    Standard Installation

    • Normal installation: pip install plotext
    • Upgrade to latest PyPi version: pip install plotext --upgrade
    • GitHub version (latest development): pip install git+https://github.com/piccolomo/plotext

    Optional Dependencies

    To enable advanced features, install the corresponding extras:

    • Image plotting (including GIFs): pip install "plotext[image]" (requires pillow)
    • Video rendering: pip install "plotext[video]" (requires opencv-python, ffpyplayer, pafy, and youtube-dl)
    • CLI TAB completion: pip install "plotext[completion]" (requires shtab)

    If installing from GitHub, use the following syntax:

    • pip install "plotext[image] @ git+https://github.com/piccolomo/plotext.git"
    • pip install "plotext[video] @ git+https://github.com/piccolomo/plotext.git"
    • pip install "plotext[completion] @ git+https://github.com/piccolomo/plotext.git"
    pip install plotext
    pip install "plotext[image]"
    pip install "plotext[video]"
    pip install "plotext[completion]"
  7. Integrate Plotext with Tkinter

    master

    Integrating Plotext into a tkinter GUI involves rendering the plot to a canvas and then displaying it in a tk.Text widget.

    Key steps:

    1. Use plt.build() to generate the plot.
    2. Access the raw canvas via plt._global.figure.monitor.matrix.canvas.
    3. Use plotext._utility.uncolorize() to strip ANSI codes for the text widget.
    4. To support colors in the GUI, iterate through the monitor matrix to get foreground and background colors, then use tk.Text tags (tag_add and tag_config) to apply colors to specific character coordinates.
  8. Handle streaming data to reduce flickering

    master

    When visualizing a continuous flow of data, use clearing methods and plt.sleep() to minimize screen flickering.

    • plt.clt(): Clears the terminal.
    • plt.cld(): Clears the data only.
    • plt.sleep(): Adds a delay between frames.
    import plotext as plt
    
    l = 1000
    frames = 200
    
    plt.title("Streaming Data")
    
    for i in range(frames):
        plt.clt() # to clear the terminal
        plt.cld() # to clear the data only
    
        y = plt.sin(periods = 2, length = l, phase = 2 * i  / frames)
        plt.scatter(y)
    
        plt.show()
  9. Create a Multiple Axes Plot

    master

    Data can be plotted on different axes using the xside and yside parameters in most plotting functions:

    • xside: Choose between "lower" or "upper" (or 1 or 2).
    • yside: Choose between "left" or "right" (or 1 or 2).

    Legend entries will include a symbol to identify which pair of axes the data belongs to.

    import plotext as plt
    
    y1 = plt.sin()
    y2 = plt.sin(2, phase = -1)
    
    plt.plot(y1, xside = "lower", yside = "left", label = "lower left")
    plt.plot(y2, xside = "upper", yside = "right", label = "upper right")
    
    plt.title("Multiple Axes Plot")
    plt.show()
  10. Verify your plotext installation

    master
    To quickly verify that your installation is working correctly (including image rendering capabilities), you can use the test() method. This function downloads a test image (cat.jpg) to your home folder and then removes it after the test is complete.
  11. Complete example: Customizing plot size, limits, and ticks

    master

    This example demonstrates how to combine plot sizing, axis limits, and custom tick labeling with mathematical notation.

    import plotext as plt
    l, p = 300, 2
    plt.plot(plt.sin(length = l, periods = p), label = "My Signal")
    plt.plotsize(100, 30)
    plt.title('Some Smart Title')
    plt.xlabel('Time')
    plt.ylabel('Movement')
    plt.ticks_color('red')
    plt.ticks_style('bold')
    plt.xlim(-l//10, l + l//10)
    plt.ylim(-1.5, 1.5)
    xticks = [l * i / (2 * p)  for i in range(2 * p + 1)]
    xlabels = [str(i) + "π" for i in range(2 * p + 1)]
    plt.xticks(xticks, xlabels)
    plt.yfrequency(5)
    plt.show()