ggstatsplot: R package for statistical plots

repository·main·Indexed 24 days ago

https://github.com/indrajeetpatil/ggstatsplot

An extension of ggplot2 that integrates statistical modeling and visualization into a single step. It automatically includes test statistics, p-values, effect sizes, and confidence intervals within plots. Supported visualizations include violin plots (ggbetweenstats, ggwithinstats), histograms (gghistostats), scatterplots (ggscatterstats), correlation matrices (ggcorrmat), and regression coefficient plots (ggcoefstats). The package supports parametric, non-parametric, robust, and Bayesian analyses.

Tokens
5.4K
Snippets
21
Records
27
Agent score
79%

What's inside ggstatsplot

  1. Overview of ggstatsplot functions and plot types

    main

    ggstatsplot is an extension of {ggplot2} that combines data visualization and statistical modeling into a single step. It produces information-rich plots that include statistical details (test statistics, p-values, effect sizes, etc.) directly within the graphics.

    Available Plot Functions

    FunctionPlot TypeDescription
    ggbetweenstats()violin plotscomparisons between groups/conditions
    ggwithinstats()violin plotscomparisons within groups/conditions
    gghistostats()histogramsdistribution of a numeric variable
    ggdotplotstats()dot plots/chartsdistribution of a labeled numeric variable
    ggscatterstats()scatterplotscorrelation between two variables
    ggcorrmat()correlation matricescorrelations between multiple variables
    ggpiestats()pie chartscategorical data
    ggbarstats()bar chartscategorical data
    ggcoefstats()dot-and-whisker plotsregression models and meta-analysis

    Note: The package also provides grouped_ versions of these functions to easily repeat analyses for a grouping variable.

  2. How Bayesian analysis is handled in ggstatsplot

    main

    For Bayesian analysis, ggstatsplot supports hypothesis testing and estimation for several common statistical procedures:

    AnalysisHypothesis testingEstimation
    (one/two-sample) t-test
    one-way ANOVA
    correlation
    (unpaired) contingency table
    (paired) contingency table
    random-effects meta-analysis
  3. Core concepts of the ggstatsplot approach

    main

    The central philosophy of {ggstatsplot} is to merge the two traditionally separate phases of data analysis—visualization and statistical modeling—into a single step.

    Instead of using visualization only to inform a model, or using a model only to describe a plot, {ggstatsplot} produces a single graphic that contains both. This approach helps researchers:

    • Evaluate the validity of statistical models by seeing them in the context of the underlying data.
    • Avoid errors in statistical reporting by embedding results directly in the plot.
    • Emphasize effect sizes by default rather than just p-values.
    • Use Bayesian methods (like Bayes factors) to evaluate the absence of an effect.

    Internally, the package uses tidyverse for data cleaning, statsExpressions and easystats for statistical analysis, and the {ggplot2} grammar of graphics for all visualizations.

  4. Install ggstatsplot

    main

    You can install the stable release of ggstatsplot from CRAN or install the development version using pak.

    Release version:

    install.packages("ggstatsplot")

    Development version:

    pak::pak("IndrajeetPatil/ggstatsplot")
    install.packages("ggstatsplot")
  5. Integrate `{ggstatsplot}` with `jamovi` via `jjstatsplot`

    main
    If you use the jamovi GUI software, you can use the jjstatsplot module, which acts as a wrapper around {ggstatsplot}, allowing you to leverage its plotting capabilities within the jamovi environment.
  6. Use statistical results with custom ggplot2 plots

    main

    If you prefer custom plots over the default {ggstatsplot} outputs, you can use {ggstatsplot} functions to extract statistical expressions and then inject them into your own {ggplot2} objects using labs(subtitle = ...).

    Example workflow:

    1. Run a {ggstatsplot} function (like ggbetweenstats) on your data.
    2. Use extract_subtitle() to get the statistical expression.
    3. Create a custom ggplot() object and pass the extracted expression to the subtitle argument in labs().
    ## loading the needed libraries
    set.seed(123)
    library(ggplot2)
    
    ## using `{ggstatsplot}` to get expression with statistical results
    stats_results <- ggbetweenstats(morley, Expt, Speed) |> extract_subtitle()
    
    ## creating a custom plot of our choosing
    ggplot(morley, aes(x = as.factor(Expt), y = Speed)) +
      geom_boxplot() +
      labs(
        title = "Michelson-Morley experiments",
        subtitle = stats_results,
        x = "Speed of light",
        y = "Experiment number"
      )
  7. Generate statistical visualizations with ggbetweenstats()

    main

    The ggbetweenstats() function is a primary tool in {ggstatsplot} that provides a one-line syntax to create {ggplot2}-based visualizations enriched with statistical details. It combines data visualization and statistical modeling into a single informative graphic.

    By default, the function produces:

    • Descriptive statistics
    • Inferential statistics
    • Effect size estimates and their uncertainty
    • Pairwise comparisons
    • Bayesian hypothesis testing
    • Bayesian posterior estimates and their uncertainty

    It is designed to display both raw data and numerical/graphical summary indices, following best practices for both data visualization and statistical reporting.

    library(palmerpenguins) # for 'penguins' dataset
    library(ggstatsplot)
    
    ggbetweenstats(penguins, species, body_mass_g)
  8. Create scatterplots with marginal distributions using ggscatterstats()

    main

    Use ggscatterstats() to create a scatterplot with marginal distributions overlaid on the axes. It includes statistical test results in the subtitle.

    To repeat this across a single grouping variable, use the grouped_ggscatterstats() variant.

    ggscatterstats(
      data  = ggplot2::msleep,
      x     = sleep_rem,
      y     = awake,
      xlab  = "REM sleep (in hours)",
      ylab  = "Amount of time spent awake (in hours)",
      title = "Understanding mammalian sleep"
    )
  9. Extract statistical expressions and data from plots

    main

    You can extract the statistical details used in {ggstatsplot} plots using the following convenience functions:

    • extract_subtitle(p): Extracts the mathematical expression used in the plot subtitle.
    • extract_caption(p): Extracts the mathematical expression used in the plot caption.
    • extract_stats(p): Returns a list of tibbles containing various statistical analysis summaries (e.g., subtitle_data, caption_data, pairwise_comparisons_data, descriptive_data, one_sample_data, tidy_data, glance_data).
    set.seed(123)
    
    p <- ggbetweenstats(mtcars, cyl, mpg)
    
    # extracting expression present in the subtitle
    extract_subtitle(p)
    
    # extracting expression present in the caption
    extract_caption(p)
    
    # a list of tibbles containing statistical analysis summaries
    extract_stats(p)
  10. Create pie charts for categorical variables with ggpiestats()

    main

    Use ggpiestats() for categorical or nominal variables.

    • If two categorical variables are provided, it performs contingency table analysis (Pearson’s chi-squared for between-subjects or McNemar’s chi-squared for within-subjects).
    • If only one categorical variable is provided, it performs a one-sample proportion test (chi-squared goodness of fit).

    To repeat this across a single grouping variable, use the grouped_ggpiestats() variant.

    set.seed(123)
    
    ggpiestats(
      data         = mtcars,
      x            = am,
      y            = cyl,
      palette      = "wesanderson::Royal1",
      title        = "Dataset: Motor Trend Car Road Tests",
      legend.title = "Transmission"
    )
  11. Visualize single variable distributions with gghistostats()

    main

    Use gghistostats() to visualize the distribution of a single variable and perform a one-sample test to check if its mean differs significantly from a specified test.value.

    To repeat this across a single grouping variable, use the grouped_gghistostats() variant.

    set.seed(123)
    
    gghistostats(
      data       = ggplot2::msleep,
      x          = awake,
      title      = "Amount of time spent awake",
      test.value = 12,
      binwidth   = 1
    )
  12. Use `ggbetweenstats()` for statistical plots

    main
    The ggbetweenstats() function is a primary entry point in {ggstatsplot} used to create plots that combine visual data representation with statistical details. It is designed to handle statistical analysis, effect sizes, and pairwise comparisons within a single function call, minimizing the need for multiple packages or manual result copying.