plottable

repository·master·Indexed 43 days ago

https://github.com/znstrider/plottable

A Python library for creating customized, presentation-ready tables within the Matplotlib framework. It allows developers to render pandas DataFrames as tables with advanced styling options, including alternating row colors, heatmap-style cell coloring via colormaps, and embedded visual plots (such as bars, donuts, and images) using the ColumnDefinition and ColDef classes.

Tokens
10.9K
Snippets
32
Records
43
Agent score
54%

What's inside plottable

  1. How to style a plottable table

    master

    There are three primary methods for customizing the appearance of a table in plottable:

    1. Keyword Arguments: Supply styling keywords directly to the Table constructor.
    2. ColumnDefinition: Provide a ColumnDefinition object for specific columns to apply granular styling.
    3. Row/Column Access: Access the table's internal rows or columns directly to apply manual modifications.
  2. Set up an editable installation for contributing

    master

    To contribute to plottable, it is recommended to use an editable installation. This allows you to make changes to the source code and see them reflected immediately without re-installing the package. Clone the repository and install it using pip install -e ..

    git clone https://github.com/znstrider/plottable.git
    cd plottable
    
    pip install -e .
  3. Format code using black

    master

    This project requires all Python code to be formatted using black before committing. You can format the entire project by running black on all .py files, or target a specific file using black <filename.py>. You can also configure your IDE to perform autoformatting with black.

    # Format all files in the directory
    black .
    
    # Format a specific file
    black <filename.py>
  4. Customize a plottable Table

    master

    There are three primary ways to customize the appearance and behavior of a table in plottable:

    1. Keyword Arguments: Supply styling keywords directly to the Table constructor.
    2. ColumnDefinition: Provide a ColumnDefinition object for specific columns to apply granular styling.
    3. Row and Column Access: Access the table's internal rows or columns directly for manual manipulation.
  5. Apply colormaps to table cells

    master

    You can colorize table cells using standard matplotlib colormaps or the normed_cmap utility.

    • normed_cmap: Useful for coloring cells based on their value relative to the distribution of the column. It takes the data column, a matplotlib colormap, and num_stds (number of standard deviations to use for normalization).
    • Standard Colormaps: You can pass a standard matplotlib.colors.Colormap directly to the cmap argument in ColumnDefinition.
    from plottable.cmap import normed_cmap
    import matplotlib.cm
    
    # Using normed_cmap for statistical coloring
    ColumnDefinition(
        name="OFF",
        cmap=normed_cmap(df["OFF"], cmap=matplotlib.cm.PiYG, num_stds=2.5),
    )
    
    # Using a custom LinearSegmentedColormap
    from matplotlib.colors import LinearSegmentedColormap
    custom_cmap = LinearSegmentedColormap.from_list("my_cmap", ["#ffffff", "#f2fbd2", "#c9ecb4"])
    ColumnDefinition(
        name="Chance",
        cmap=custom_cmap,
    )
  6. Create custom formatter functions

    master

    You can create custom formatters by defining a function that accepts a cell value and returns a formatted string or number. This can be a standard function or a lambda expression.

    Signature for a custom function:

    def my_formatter(cell_content: Any) -> str | Number: ...
    # Using a lambda for simple rounding
    tab = Table(d, column_definitions=[ColDef(name="A", formatter=lambda x: round(x, 1))])
  7. Create custom plot functions for plottable

    master

    You can create custom plots by defining a function with a specific signature. The first argument must be a matplotlib.axes.Axes object, and the second must be the cell's value (val). Any additional arguments will be provided via the plot_kw parameter in ColumnDefinition.

    For complex data, your function can use the cell value to look up data in a dictionary or call a getter function.

    import matplotlib.pyplot as plt
    from typing import Any
    
    def custom_plot_fn(ax: plt.Axes, val: Any, **kwargs):
        # Use kwargs passed from plot_kw
        color = kwargs.get("color", "blue")
        
        # Logic to get complex data based on cell value
        data = my_data_dict.get(val)
        
        # Perform matplotlib operations on ax
        ax.bar(data)
  8. Color column cells using ColorMaps

    master

    You can apply background coloring to the cells of a specific column by providing a cmap argument to its ColumnDefinition. The cmap argument accepts either a Callable or a LinearSegmentedColormap. This allows the background color of each cell to be determined dynamically based on its underlying value.

    # Example concept (requires ColumnDefinition context)
    ColumnDefinition(
        name="column_name",
        cmap=my_colormap  # Can be a Callable or LinearSegmentedColormap
    )
  9. Format cell values in plots using strings or functions

    master

    You can format how numeric values are displayed within a plot by passing a formatter key inside the plot_kw dictionary of a ColumnDefinition.

    There are two ways to provide a formatter:

    1. Python formatting syntax: Pass a standard Python format string (e.g., "{:.0%}").
    2. Formatter functions: Pass a callable function (e.g., decimal_to_percent from plottable.formatters).
    # Using a format string
    ColumnDefinition(
        "C",
        plot_fn=progress_donut,
        plot_kw={
            "is_pct": True,
            "formatter": "{:.0%}"
        },
    )
    
    # Using a formatter function
    from plottable.formatters import decimal_to_percent
    ColumnDefinition(
        "D",
        plot_fn=bar,
        plot_kw={
            "formatter": decimal_to_percent,
        },
    )
  10. Set column titles, widths, and text properties

    master

    Use ColumnDefinition to override the display name, adjust the width relative to the default, or change font attributes via textprops.

    • Title: Use title="New Name".
    • Width: Use width=2.0 to make a column twice as wide as the default.
    • Textprops: Pass a dictionary of matplotlib text properties like {"ha": "left", "weight": "bold"}.
    import matplotlib.pyplot as plt
    import numpy as np
    import pandas as pd
    from plottable import ColumnDefinition, Table
    
    d = pd.DataFrame(np.random.random((5, 5)), columns=["A", "B", "C", "D", "E"]).round(2)
    fig, ax = plt.subplots(figsize=(6, 5))
    
    # Example: Custom title, width, and text properties
    tab = Table(d, column_definitions=[
        ColumnDefinition(name="A", title="Title A", width=2),
        ColumnDefinition(name="index", textprops={"ha": "left", "weight": "bold"})
    ])
    
    plt.show()