PtitPrince

repository·master·Indexed 43 days ago

https://github.com/pog87/ptitprince

A Python implementation of Raincloud plots, built on top of Seaborn. Version 0.3.1 provides tools for robust data visualization by combining half-violin plots (clouds), stripplots (rain), and boxplots (umbrellas) into a single composite plot. It includes a high-level RainCloud API and specialized functions like half_violinplot and stripplot with custom movement offsets.

Tokens
3.2K
Snippets
11
Records
15
Agent score
56%

What's inside PtitPrince

  1. Configure component styles via prefixed kwargs

    master

    In versions 0.2.x and later, you can pass keyword arguments (kwargs) to specific components of the plot (cloud, boxplot, rain/stripplot, or pointplot) by prefixing the argument name with the component identifier:

    • cloud_ for the cloud component (default)
    • box_ for the boxplot component
    • rain_ for the rain/stripplot component
    • point_ for the pointplot component
  2. Install ptitprince

    master

    You can install the ptitprince package using pip, conda, or directly from the GitHub repository.

    # Via pip
    pip install ptitprince
    
    # Via conda
    conda install -c conda-forge ptitprince
    
    # Directly from GitHub
    pip install git+https://github.com/pog87/PtitPrince
  3. How to customize Raincloud plot components

    master

    You can fine-tune the visual properties of the Raincloud plot using several parameters in pt.RainCloud:

    • Smoothness: Adjust the bw parameter to change the smoothing kernel of the probability distribution function.
    • Orientation: Use orient='v' for vertical plots (often called 'petit prince' plots) or orient='h' for horizontal plots.
    • Rain Position: Use the move parameter to shift the raw data points (the rain) below the boxplot to improve visibility.
    • Subgroup Comparison: Use the hue parameter to plot different sub-groups. Combine this with dodge=True to prevent boxplots from obscuring one another and alpha to adjust transparency for better readability.
    # Example: Vertical plot with shifted rain and dodging for subgroups
    ax = pt.RainCloud(
        x="group",
        y="score",
        hue="subgroup",
        data=df,
        orient="v",
        move=0.2,
        dodge=True,
        alpha=0.65
    )
  4. How Raincloud plots handle hue and subgroups

    master

    The raincloud function behaves differently depending on whether the hue variable represents a true subgroup or just a coloring preference:

    1. True Subgroups: If hue is a different variable than the categorical axis (x or y), the plot creates distinct clouds and rain points for each hue level. In this mode, boxplots are filled to help distinguish overlapping subgroups.
    2. Coloring Only: If hue is the same as the categorical axis, it is treated as a coloring preference. The boxplots remain transparent (facecolor='none') to avoid clutter, and the legend is automatically removed to prevent redundancy with the axis labels.

    Legend Behavior:

    • If hue creates subgroups, a legend is generated with the hue name as the title, positioned to the right of the plot.
    • If hue is redundant with the axis, the legend is removed.
  5. Create a Raincloud plot

    master

    A Raincloud plot is a composite visualization consisting of four elements:

    1. Cloud: A kernel density estimate (half of a half_violinplot).
    2. Rain: A stripplot representing individual data points.
    3. Umbrella: A boxplot showing summary statistics.
    4. Thunder (Optional): A pointplot connecting the means of different categories if pointplot=True.

    Main Arguments

    • x: Categorical data (Iterable, np.array, or dataframe column name).
    • y: Measure data (Iterable, np.array, or dataframe column name).
    • hue: Second categorical variable for subgroups (creates different clouds and rain points).
    • data: Input pandas DataFrame.
    • order: List defining the order of categorical data.
    • hue_order: List defining the order of the hue.
    • orient: Orientation, either 'v' (vertical, default) or 'h' (horizontal).
    • width_viol: Width of the cloud.
    • width_box: Width of the boxplot.
    • move: Adjusts rain position relative to the x-axis (default 0.0).
    • offset: Adjusts cloud position relative to the x-axis.

    Customizing Components via kwargs

    You can pass specific arguments to the underlying components by prefixing the argument name with the component type:

    • cloud_: Arguments for the half-violin/cloud component.
    • box_: Arguments for the boxplot component.
    • rain_: Arguments for the stripplot/rain component.
    • point_: Arguments for the pointplot component.
    • Unprefixed kwargs are passed to the cloud component by default.
    # Example usage (conceptual based on API description)
    raincloud(x='category', y='value', data=df, pointplot=True, rain_size=3, cloud_bw=0.5)
  6. Visualize factorial effects with pointplots

    master

    To emphasize factorial effects or longitudinal data (repeated measures), set pointplot=True in the pt.RainCloud function. This adds a line connecting the mean values of the groups, helping to detect trends across categories or timepoints.

    # Adding a line connecting the groups' mean value
    ax = pt.RainCloud(
        x="group",
        y="score",
        data=df,
        palette="Set2",
        hue="group",
        bw=0.2,
        width_viol=0.6,
        ax=ax,
        orient="h",
        pointplot=True,
    )
  7. Integrate RainCloud with Seaborn FacetGrid

    master

    You can use pt.RainCloud within a Seaborn FacetGrid to create multiple plots separated by a factor level. Use g.map_dataframe to pass the RainCloud function to the grid.

    # Rainclouds with FacetGrid
    g = sns.FacetGrid(df, col="gr2", height=6)
    g = g.map_dataframe(pt.RainCloud, x="group", y="score", data=df, orient="h", hue="group")
    
    for ax in g.axes.flat:
        ax.set_xlabel("")
        ax.set_ylabel("")
  8. Use pt.RainCloud with list or numpy array inputs

    master

    While pt.RainCloud is designed for pandas DataFrames, it also supports passing raw lists or numpy arrays for the x and y parameters directly.

    # Usage with a list/np.array input
    dx = list(df["group"])
    dy = list(df["score"])
    f, ax = plt.subplots(figsize=(7, 5))
    
    ax = pt.RainCloud(x=dx, y=dy, palette=pal, bw=sigma, width_viol=0.6, ax=ax, orient=ort)
  9. Use stripplot with custom movement

    master

    The stripplot function is a wrapper around seaborn.stripplot that adds a move parameter. This allows you to shift the points along the categorical axis to create custom offsets, which is useful when combining multiple plot types (like Raincloud plots) to prevent overlapping.

    Key parameters:

    • move: A float that shifts the strip plot along the categorical axis. Positive values move points in the positive direction.
    • dodge: If True, points are dodged based on the hue variable. This implementation ensures the dodge width matches the user-specified width parameter.
    • jitter: Boolean to enable/disable jittering.
    • size: Size of the points.
    • edgecolor: Color of the point edges (defaults to 'gray').
    import ptitprince
    import matplotlib.pyplot as plt
    
    # Example usage with movement to avoid overlap
    ax = ptitprince.stripplot(x='category', y='value', data=df, move=0.2, jitter=True)
    plt.show()
  10. Use the PtitPrince public API

    master

    The ptitprince package exports its primary functionality from the PtitPrince class via the package entrypoint. You can access all available methods and attributes by importing from the top-level ptitprince module.

    import ptitprince
    
    # All exported symbols from the PtitPrince class are available here
  11. Use RainCloud plots

    master

    The RainCloud function generates a Raincloud plot, which combines a half-violin plot, a boxplot (or similar), and a strip plot to provide a comprehensive view of data distribution, central tendency, and individual observations.

    Key parameters:

    • x, y: Categorical and numeric data.
    • hue: Semantic variable for coloring.
    • width_viol: Width of the violin component.
    • width_box: Width of the boxplot component.
    • pointplot: Boolean to include/exclude the strip plot component.
    • move: Shift for the strip plot component.
    • offset: Offset for the violin component.
    • dodge: Whether to dodge components based on hue.
    import ptitprince
    import matplotlib.pyplot as plt
    
    # Example usage
    ax = ptitprince.RainCloud(x='category', y='value', data=df, pointplot=True)
    plt.show()