Skip to main content
v2026.11,986 entries · CC-BY 4.0

Posterior Predictive Check: How to Run and Read One in R and Python

Run a posterior predictive check in brms, bayesplot or PyMC, pick the right plot family, and read what a mismatch says about your model.

Written and maintained by CASRAI Editorial Board

Published

On this page

A posterior predictive check is a test of a fitted Bayesian model: you use the model to simulate new datasets from its posterior distribution, then compare those simulated datasets with the data you actually observed. If the model fits well, the observed data should look like a typical draw from the simulations; if it does not, the way it stands out shows what the model misses. The bayesplot package documentation puts the idea in one sentence: if a model is a good fit, “we should be able to use it to generate data that looks a lot like the data we observed.”

What a posterior predictive check is used for in research

Researchers run a posterior predictive check after a model has been fitted, usually by Markov chain Monte Carlo, to ask whether the model can reproduce the main features of the data it was fitted to. Convergence diagnostics tell you whether the sampler explored the posterior; a posterior predictive check tells you whether the model that posterior belongs to is a reasonable description of the data. The two questions are different, and a model can pass the first and fail the second.

The mechanics, as the bayesplot documentation describes them, are these. For each draw of the parameters θ from the posterior p(θ | y, X), you generate an entire vector of outcomes. With S posterior draws and N data points, the result is an S × N matrix, and each row is one replicated dataset, written yrep in the notation of Gelman et al. (2013). If you reuse the same predictors X, the rows are replications of the observed data. If you supply new predictor values, the rows are predictions instead.

Posterior predictive check versus prior predictive check

A prior predictive check follows the same logic but draws from the prior predictive distribution instead of the posterior, so it needs no fitted model and no observed outcomes. It asks whether the priors you chose imply data that are scientifically plausible, which is why bayesplot’s prior predictive plots take no observed-data argument (Gabry et al. 2019 is the reference the bayesplot documentation gives). Run the prior version before fitting and the posterior version after. For the distinction between the distributions themselves, see the comparison of prior and posterior, and for what to do when a prior drives the result, see prior sensitivity analysis.

How to install or access the tools

Posterior predictive checks are not a single program. They are a workflow supported by several open-source packages. Install them from their official sources.

  • bayesplot (R). From CRAN: install.packages("bayesplot"). The development version installs from GitHub with devtools::install_github("stan-dev/bayesplot", dependencies = TRUE, build_vignettes = FALSE), as listed on the package site.
  • brms (R). Its pp_check() method for fitted models calls bayesplot internally, so both packages are needed for brms users.
  • PyMC (Python). The installation page gives pip install pymc, or pip install "pymc[nutpie]" to include the nutpie sampler, or a conda route: conda create -c conda-forge -n pymc_env "pymc>=6" followed by conda activate pymc_env.

How to run a posterior predictive check step by step

The steps below work in either language. The commands shown are the ones in the current package documentation.

  1. Fit the model. Fit it to your data and confirm that the sampler converged before interpreting any check.
  2. Generate replicated datasets. Draw one simulated dataset per posterior draw. In PyMC this is pm.sample_posterior_predictive, which the documentation describes as generating “forward samples for var_names, conditioned on the posterior samples of variables found in the trace,” and which can be used for “different kinds of model predictions, including posterior predictive checks.” Observed random variables that are missing from the trace are always regenerated automatically. In brms and bayesplot, the replication happens inside pp_check().
  3. Choose a plot that targets a feature you care about. A whole-distribution overlay is the usual first look; test-statistic, interval and discrete plots address more specific features (see the data table below).
  4. Compare observed with replicated. Look for features of the real data that the simulated datasets rarely or never show.
  5. Revise or accept. If the mismatch matters for your research question, change the likelihood, add structure, or revisit the priors, then refit and check again.

In R with brms

For a fitted brms model, the signature in brms 2.23.2 is pp_check(object, type, ndraws = NULL, prefix = c("ppc","ppd"), group = NULL, x = NULL, newdata = NULL, resp = NULL, draw_ids = NULL, ...). It returns a ggplot object. The brms documentation’s own example fits a Poisson model to the epilepsy data:

fit = brm(count ~ zAge + zBase * Trt + (1 | patient) + (1 | obs),           data = epilepsy, family = poisson())pp_check(fit, ndraws = 50)

Set prefix = "ppd" to produce the same display without the observed data. The group argument is required for the grouped plot types. If you pass an unsupported type, the error lists the types your version supports, which is a quick way to see the options.

In R with bayesplot directly

When you hold the data and draws yourself, every bayesplot posterior predictive plot function starts with ppc_ and requires y, a vector of observations, and yrep, a matrix of replications. The generic wrapper in bayesplot 1.16.0 is pp_check(object, yrep, fun, ...); the documentation examples include:

pp_check(y, yrep[1:50, ], ppc_dens_overlay)pp_check(y, yrep, fun = "stat_grouped", group = g, stat = "median")

The first overlays the density of the first 50 replicated datasets on the observed density. The second compares the group-wise median of the data with the distribution of that median across replications. When fun is given as a string, the ppc_ prefix is optional.

In Python with PyMC

After sampling, pass the sampling result and the model to the posterior predictive function:

with model:    ppc = pm.sample_posterior_predictive(idata)

The documented parameters are trace, model, sample_vars and freeze_vars. Plotting then happens in ArviZ, whose plotting functions now live in the arviz_plots package; its posterior predictive plot is arviz_plots.plot_ppc_dist.

How to read the output

The central question is whether the observed data look like one of the replicated datasets. How you ask depends on the plot family. The data table below lists each bayesplot family and what it compares. Read these with the model’s purpose in mind: a visible discrepancy matters only if it concerns a feature your research question depends on.

Distribution overlays

These compare the empirical distribution of the observed data with the distributions of individual simulated datasets. If the observed curve sits inside the band of replicated curves, the model captures the overall shape. If the observed curve has a heavier tail, a second mode, or a spike at zero that the replicates lack, the likelihood is the first thing to question.

Test-statistic plots

These show the distribution of a chosen statistic, for example a median, a maximum or a proportion of zeros, across the replications, with the value calculated from the observed data marked. An observed value in the far tail of the replicated distribution means the model rarely produces data with that feature. Choosing a statistic that the model was not directly fitted to match is what makes this check informative.

Interval and error plots

Interval plots show interval estimates of the replicated values with the observed outcomes overlaid, optionally against a chosen x-axis variable. Error plots show predictive errors, y − yrep. Both help locate where along a predictor the model fits poorly.

Discrete outcomes

For counts and categorical data, the discrete family provides rootograms for counts and bar plots for ordinal, categorical and multinomial outcomes. A binary-outcome calibration family and leave-one-out and censoring families also exist.

Worked reading

Suppose a count model’s density overlay shows the observed data with far more zeros than any replicated dataset, while a test-statistic plot of the proportion of zeros places the observed value outside the replicated distribution. Both plots point to the same feature, so the likelihood is a poor description of how zeros arise. Changing the family and refitting, then repeating the same two plots, would show whether the revised model reproduces that feature. This is an illustration of the reasoning, not a result from a specific dataset.

A good-looking posterior predictive check does not prove the model correct, and does not by itself justify its priors. For the wider workflow, including how models of this type are specified, see the guide to Bayesian regression.

Troubleshooting posterior predictive checks

  • The plot function complains about the arguments. bayesplot’s ppc_ functions need y as a vector and yrep as a matrix with one row per replicated dataset (S rows, N columns). A transposed matrix is the usual cause.
  • The overlay is unreadable. Plot a subset of the draws, as the documented example does with yrep[1:50, ], or use ndraws in pp_check() for brms.
  • The grouped plot fails in brms. The group argument is required for the grouped types.
  • An unknown type is rejected. The error message from brms lists the supported types.
  • PyMC returns no predictions for an observed variable. Observed random variables missing from the trace are regenerated automatically, so check that the model passed in is the one that produced the trace.
  • The check looks fine but the model is questionable. The check only addresses the features you plotted. Try a different statistic, then see the guide to NumPyro or another sampler if you want to test the same model with different inference software.

Other tools that run a posterior predictive check

The same check can be run from several open-source packages. The table lists the entry point each package documents for it.

Package Language Documented entry point
bayesplot R pp_check(object, yrep, fun, ...) and the ppc_ plot functions
brms R pp_check() method for fitted models; prefix = "ppd" hides the observed data
PyMC Python pymc.sample_posterior_predictive
ArviZ (arviz_plots) Python arviz_plots.plot_ppc_dist for plotting

Choose by the language and sampler your analysis already uses; the logic of the check does not change between them.

Sources

Data: bayesplot posterior predictive check plot families and what each compares

Compilation of the posterior predictive check plot families documented in the bayesplot PPC overview, giving what each family compares and any restriction on the outcome type, compiled from the package documentation.

bayesplot posterior predictive check plot families and what each compares
Plot familyWhat it comparesOutcome restriction
PPC-distributionsEmpirical distribution of y against distributions of individual simulated datasetsNone stated
PPC-test-statisticsDistribution of a statistic (or pair) across replications against the value computed from yNone stated
PPC-intervalsInterval estimates of yrep with y overlaid, optionally against a chosen x-axis variableNone stated
PPC-errorsPredictive errors y - yrep, including binned error plots for binomial modelsNone stated
PPC-scatterplotsy against individual simulated datasets, or against the average predicted value per data pointNone stated
PPC-discreteRootograms for counts; bar plots for ordinal, categorical and multinomial outcomesDiscrete y and yrep only
PPC-looPredictive checks based on (approximate) leave-one-out cross-validationNone stated
PPC-censoringEmpirical distribution of censored y against distributions of simulated datasetsCensored outcomes
PPC-calibrationCalibration of predictions or predictive probabilities against observationsBinary outcomes

Sources

Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Ask CASRAI · full access

Ask about Posterior Predictive Check: How to Run and Read One in R and Python

Full access: large monthly usage, up to 10 source passages behind each answer, and MCP and API access for Claude Code, Codex and other CLIs. Cancel any time.

An AI assistant for research: funder rules, compliance, methods and publishing. It links the sources behind its answers and labels answers that come from a web search.

Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.

Works on this site and inside Claude, Cursor and the AI tools you already use.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays open to read, with no account and no card.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →