forestplot

repository·main·Indexed 41 days ago

https://github.com/lsys/forestplot

A Python package for creating publication-ready, customizable forest plots from pandas DataFrames. It allows for mapping statistical estimates and confidence intervals to visual representations, supporting features like variable grouping, sorting, p-value reporting, and table-style annotations. Includes an experimental mforestplot function for comparing multiple regression models side-by-side.

Tokens
7.1K
Snippets
15
Records
21
Agent score
50%

What's inside forestplot

  1. Install forestplot

    main

    You can install forestplot using pip, conda, or by installing from source.

    Using pip:

    pip install forestplot

    Using conda-forge:

    conda install forestplot

    From source:

    git clone https://github.com/LSYS/forestplot.git
    cd forestplot
    pip install .
  2. Quick Start with forestplot

    main

    To create a forest plot, provide a pandas DataFrame containing your study results. The core workflow involves loading or preparing your data and then calling fp.forestplot() with specific column mappings.

    Basic Usage Example

    import forestplot as fp
    import matplotlib.pyplot as plt
    
    # Load example data
    df = fp.load_data("sleep")
    
    # Generate the forest plot
    fp.forestplot(
        df, 
        estimate="r",      # Column containing estimated effect size 
        ll="ll",          # Column containing confidence interval lower limits
        hl="hl",          # Column containing confidence interval higher limits
        varlabel="label", # Column containing variable labels
        ylabel="Confidence interval",
        xlabel="Pearson correlation"
    )
    
    # Save the plot using matplotlib
    plt.savefig("plot.png", bbox_inches="tight")
    import forestplot as fp
    
    df = fp.load_data("sleep")  # companion example data
    df.head(3)
    
    fp.forestplot(df,  # the dataframe with results data
                  estimate="r",  # col containing estimated effect size 
                  ll="ll", hl="hl",  # columns containing conf. int. lower and higher limits
                  varlabel="label",  # column containing variable label
                  ylabel="Confidence interval",  # y-label title
                  xlabel="Pearson correlation",  # x-label title
                  )
  3. Troubleshoot known issues in forestplot

    main

    Be aware of the following known limitations and behaviors:

    • Formatting: Left-flushing of annotations relies on the monospace font. Variable labels coinciding with group variables may cause unexpected formatting.
    • Data Volume: The plot may behave strangely with very few rows (6 or fewer) and can become cluttered if there are too many variables (~30 or more).
    • Data Integrity: Duplicated varlabel entries may lead to unexpected results.
    • Environment: The package has not been explicitly tested with PyCharm or Google Colab.
  4. Format forest plots as tables with annotations

    main

    You can transform the forest plot into a table format by setting table=True. This allows you to include detailed annotations on both the left and right sides of the plot.

    • annote: List of columns to report on the left of the plot.
    • annoteheaders: Corresponding headers for the left annotations.
    • rightannote: List of columns to report on the right of the plot.
    • right_annoteheaders: Corresponding headers for the right annotations.
    fp.forestplot(df,  # the dataframe with results data
                  estimate="r",  # col containing estimated effect size 
                  ll="ll", hl="hl",  # lower & higher limits of conf. int.
                  varlabel="label",  # column containing the varlabels to be printed on far left
                  capitalize="capitalize",  # Capitalize labels
                  pval="p-val",  # column containing p-values to be formatted
                  annote=["n", "power", "est_ci"],  # columns to report on left of plot
                  annoteheaders=["N", "Power", "Est. (95% Conf. Int.)"],  # ^corresponding headers
                  rightannote=["formatted_pval", "group"],  # columns to report on right of plot 
                  right_annoteheaders=["P-value", "Variable group"],  # ^corresponding headers
                  xlabel="Pearson correlation coefficient",  # x-label title
                  table=True,  # Format as a table
                  )
  5. Use mforestplot for multi-model coefficient plots

    main

    When each variable has multiple estimates (e.g., from different models), use mforestplot. This function allows you to compare models side-by-side.

    Key parameters:

    • model_col: The column identifying the model.
    • modellabels: Labels for the different models.
    • mcolor: A list of colors to assign to each model.
    • offset: Controls the vertical offset between models (0.0 to 1.0).

    Note: This module is currently experimental.

    fp.mforestplot(
        dataframe=df_mmodel,
        estimate="coef",
        ll="ll",
        hl="hl",
        varlabel="label",
        capitalize="capitalize",
        model_col="model",
        color_alt_rows=True,
        groupvar="group",
        table=True,
        rightannote=["var", "group"],
        right_annoteheaders=["Source", "Group"],
        xlabel="Coefficient (95% CI)",
        modellabels=["Have young kids", "Full sample"],
        xticks=[-1200, -600, 0, 600],
        mcolor=["#CC6677", "#4477AA"],
        # Additional kwargs for customizations
        **{
            "markersize": 30,
            # override default vertical offset between models (0.0 to 1.0)
            "offset": 0.35,  
            "xlinestyle": (0, (10, 5)),  # long dash for x-reference line
            "xlinecolor": ".8",  # gray color for x-reference line
        },
    )
  6. Customize forest plots with groupings and sorting

    main

    You can organize your forest plot by adding variable groupings and controlling their order. Using groupvar specifies the column containing group labels, and group_order allows you to define the specific sequence of those groups. Additionally, setting sort=True will sort the estimates in ascending order within each group.

    fp.forestplot(df,  # the dataframe with results data
                  estimate="r",  # col containing estimated effect size 
                  ll="ll", hl="hl",  # columns containing conf. int. lower and higher limits              
                  varlabel="label",  # column containing variable label
                  capitalize="capitalize",  # Capitalize labels
                  groupvar="group",  # Add variable groupings 
                  # group ordering
                  group_order=["labor factors", "occupation", "age", "health factors", 
                               "family factors", "area of residence", "other factors"],
                  sort=True  # sort in ascending order (sorts within group if group is specified)               
                  )
  7. Add p-values and alternate row coloring

    main

    To enhance readability, you can display p-values on the right side of the plot and apply gray shading to alternate rows. Use pval to specify the column containing p-values and color_alt_rows=True to enable shading. You can also customize the y-axis label using ylabel and control its size via keyword arguments like ylabel1_size.

    fp.forestplot(df,  # the dataframe with results data
                  estimate="r",  # col containing estimated effect size 
                  ll="ll", hl="hl",  # columns containing conf. int. lower and higher limits
                  varlabel="label",  # column containing variable label
                  capitalize="capitalize",  # Capitalize labels
                  groupvar="group",  # Add variable groupings 
                  # group ordering
                  group_order=["labor factors", "occupation", "age", "health factors", 
                               "family factors", "area of residence", "other factors"],
                  sort=True,  # sort in ascending order (sorts within group if group is specified)               
                  pval="p-val",  # Column of p-value to be reported on right
                  color_alt_rows=True,  # Gray alternate rows
                  ylabel="Est.(95% Conf. Int.)",  # ylabel to print
                  **{"ylabel1_size": 11}  # control size of printed ylabel
                  )
  8. Retrieve processed data using return_df

    main

    To see how forestplot processes your columns (especially for annotations), you can set return_df=True. This returns both the processed DataFrame and the axes object. The processed DataFrame contains several new columns used for formatting, such as ci_range, est_ci, and formatted_pval.

    processed_df, ax = fp.forestplot(df, 
                                       ...  # other arguments here
                                       return_df=True  # return processed dataframe with processed columns
                                      )
    processed_df.head(3)
  9. Configure forestplot table annotations and headers

    main

    When calling fp.forestplot with table=True, you can use several keyword arguments to customize the data reported in the table alongside the plot:

    • estimate: Column name for the estimate (e.g., `
  10. Reference: Available Annotation Formats

    main

    When using the annote or rightannote arguments, you can reference these pre-processed column names in your DataFrame:

    • ci_range: Confidence interval range (e.g. (-0.39 to -0.25)).
    • est_ci: Estimate and CI (e.g. -0.32(-0.39 to -0.25)).
    • formatted_pval: Formatted p-values (e.g. 0.01**).
  11. Dataframe requirements for forestplot

    main

    When preparing a DataFrame for forestplot, ensure you have the required columns and optionally include others for annotations.

    ColumnDescriptionRequired
    varVariable label✅
    rCorrelation coefficients (estimates to plot)✅
    labelVariable labels✅
    groupVariable grouping labels
    llConfidence interval lower limits
    hlConfidence interval higher limits
    nSample size
    powerStatistical power
    p-valP-value