pynimate Documentation

repository·main·Indexed 18 days ago

https://github.com/julkaar9/pynimate

A Python package for creating statistical data animations, such as bar chart races and animated line plots, using pandas DataFrames and matplotlib. It provides tools for data interpolation via Datafiers, custom styling including dark mode, and the ability to export animations as GIF or MP4 files.

Tokens
11.7K
Snippets
45
Records
53
Agent score
62%

What's inside pynimate

  1. Use plot-specific datafiers instead of Datafier

    main
    The pynimate.datafier.Datafier class is deprecated. Developers should avoid using the general Datafier class and instead use the specific datafiers designed for individual plot types (e.g., bar chart datafiers, line chart datafiers) to ensure compatibility and correct data handling.
  2. Extend BaseDatafier to create custom datafiers

    main
    The pynimate.datafier.BaseDatafier class serves as the base class for creating custom datafiers in Pynimate. When implementing a new datafier, you should inherit from this class to ensure compatibility with the Pynimate processing pipeline. While the specific implementation details of the base class are internal, it provides the foundation for handling data transformations and documentation generation within the library.
  3. Prepare data for Pynimate

    main

    Pynimate requires data to be formatted as a pandas.DataFrame where the time column is set as the index. The columns represent the values to be animated over time.

    # Example of the required DataFrame structure:
    # The time column must be the index
    time, col1, col2, col3
    2012   1     2     1
    2013   1     1     2
    2014   2     1.5   3
    2015   2.5   2     3.5
  4. Create a dark themed Animated Line plot

    main

    To create a dark-themed animation, you must configure matplotlib.rcParams to set the figure, axes, and savefig facecolors to your desired dark color (e.g., #001219) and remove the axes spines. Additionally, ensure all text elements (labels, titles, legends, ticks) are explicitly set to a light color like 'w' (white) using the plot's setter methods.

    import matplotlib as mpl
    import pynimate as nim
    
    # 1. Setup Matplotlib dark theme
    for side in ["left", "right", "top", "bottom"]:
        mpl.rcParams[f"axes.spines.{side}"] = False
    mpl.rcParams["figure.facecolor"] = "#001219"
    mpl.rcParams["axes.facecolor"] = "#001219"
    mpl.rcParams["savefig.facecolor"] = "#001219"
    
    # 2. Prepare Data
    df = pd.read_csv("data.csv").set_index("time")
    dfr = nim.LineDatafier(df, "%Y-%m-%d", "12h")
    
    # 3. Define post_update callback
    def post(self, i):
        self.ax.yaxis.set_major_formatter(tick.FuncFormatter(lambda x, pos: human_readable(x)))
    
    # 4. Initialize Plot
    plot = nim.Lineplot(
        dfr,
        post_update=post,
        palettes=["Set3"],
        scatter_markers=False,
        legend=True,
        fixed_ylim=True,
        grid=False,
    )
    
    # 5. Apply styling for dark mode
    plot.set_title("Title", color="w")
    plot.set_xlabel("xlabel", color="w")
    plot.set_time(callback=lambda i, datafier: ..., color="w")
    plot.set_legend(labelcolor="w")
    plot.set_xticks(colors="w")
    plot.set_yticks(colors="w")
    
    # 6. Animate
    cnv = nim.Canvas()
    cnv.add_plot(plot)
    cnv.animate()
  5. Create a dark themed bar chart race

    main

    To create a dark-themed animation, you should configure both Matplotlib's global parameters and the pynimate objects.

    1. Matplotlib Setup: Set axes.facecolor and disable spines using mpl.rcParams.
    2. Canvas Setup: Initialize nim.Canvas with a facecolor matching your theme.
    3. Plot Styling:
      • Use set_column_colors() to pass a dictionary of hex colors for specific categories.
      • Use set_title, set_xlabel, set_xticks, and set_yticks with color="w" (white) to ensure text visibility.
      • Use set_time and set_text with callbacks to dynamically update text colors in sync with the animation.
    import matplotlib as mpl
    import pynimate as nim
    
    # 1. Matplotlib global dark theme
    mpl.rcParams["axes.facecolor"] = "#001219"
    for side in ["left", "right", "top", "bottom"]:
        mpl.rcParams[f"axes.spines.{side}"] = False
    
    # 2. Data and Colors
    df = pd.DataFrame(...).set_index("time")
    bar_cols = {"Afghanistan": "#2a9d8f", "Angola": "#e9c46a", ...}
    
    # 3. Pynimate setup
    cnv = nim.Canvas(figsize=(12.8, 7.2), facecolor="#001219")
    dfr = nim.BarDatafier(df, "%Y-%m-%d", "3d")
    bar = nim.Barhplot(dfr, rounded_edges=True, grid=False)
    
    # 4. Apply styling
    bar.set_column_colors(bar_cols)
    bar.set_title("Sample Title", color="w", weight=600)
    bar.set_xticks(colors="w", length=0, labelsize=13)
    
    cnv.add_plot(bar)
    cnv.animate()
  6. How rank interpolation (ip_frac) works

    main

    To prevent bars from jumping erratically in animations, pynimate can interpolate the ranks of columns.

    When ip_frac is set (e.g., 0.5), a percentage of the NaN gaps in the rank data will be linearly interpolated using the ip_method. The remaining gaps are filled using the ip_fill_method (defaulting to 'bfill').

    Example Scenario: If you have data at 2021-11-13 and 2021-11-18 with NaNs in between:

    • ip_frac=0.5 means 50% of the gap is filled via linear interpolation.
    • The rest is filled via the backfill/forwardfill method.

    This creates a smoother transition for the bar positions in a barChartRace.

  7. Customize animation frames with post_update

    main

    The post_update parameter accepts a callable that is executed at every frame of the animation. This allows for dynamic adjustments to the plot, such as changing scales or adding custom logic based on the current frame index.

    Arguments for post_update:

    • self: The Baseplot instance.
    • i: The current frame index (integer).

    Example of setting a log scale for the x-axis during updates:

    def post_update(self, i):
        # sets log scale for x-axis
        self.ax.set_xscale("log")
    
    # Pass this to Baseplot constructor
    plot = Baseplot(datafier=my_datafier, post_update=post_update)
  8. Initialize Barplot for animated bar charts

    main

    The Barplot class creates an animated bar chart (BarChartRace).

    Note: Barplot is deprecated. Use Barhplot instead.

    To use Barplot, provide a pd.DataFrame where the index is a time component. The data should be formatted such that columns represent the categories being ranked and the index represents time steps.

    import pandas as pd
    from pynimate.bar import Barplot
    
    # Example data format
    data = pd.DataFrame({
        'col1': [1, 2, 3],
        'col2': [0, 3, 1]
    }, index=pd.to_datetime(['2012-01-01', '2013-01-01', '2014-01-01']))
    
    plot = Barplot(
        data=data,
        time_format='%Y-%m-%d',
        ip_freq='D',
        n_bars=10,
        palettes=['viridis']
    )
    import pandas as pd
    from pynimate.bar import Barplot
    
    data = pd.DataFrame({
        'col1': [1, 2, 3],
        'col2': [0, 3, 1]
    }, index=pd.to_datetime(['2012-01-01', '2013-01-01', '2014-01-01']))
    
    plot = Barplot(
        data=data,
        time_format='%Y-%m-%d',
        ip_freq='D',
        n_bars=10,
        palettes=['viridis']
    )