### Install Development Dependencies Source: https://mc-stan.org/bayesplot/CONTRIBUTING.html Installs all necessary development dependencies for the package. It's recommended to run this before checking the package. ```R devtools::install_dev_deps() ``` -------------------------------- ### Default pp_check Method Example Source: https://mc-stan.org/bayesplot/reference/pp_check.html Demonstrates using the default pp_check method with density overlay and grouped statistics plots. Ensure example data functions are available. ```R y <- example_y_data() yrep <- example_yrep_draws() pp_check(y, yrep[1:50,], ppc_dens_overlay) g <- example_group_data() pp_check(y, yrep, fun = "stat_grouped", group = g, stat = "median") ``` -------------------------------- ### Example: Overlaying censored data PPC Source: https://mc-stan.org/bayesplot/reference/PPC-censoring.html Demonstrates how to use ppc_km_overlay with example data. It shows how to prepare censored data (y, status_y) and then plots the overlay of empirical and posterior predictive distributions. ```R color_scheme_set("brightblue") # For illustrative purposes, (right-)censor values y > 110: y <- example_y_data() status_y <- as.numeric(y <= 110) y <- pmin(y, 110) # In reality, the replicated data (yrep) would be obtained from a # model which takes the censoring of y properly into account. Here, # for illustrative purposes, we simply use example_yrep_draws(): yrep <- example_yrep_draws() dim(yrep) #> [1] 500 434 # Overlay 25 curves ppc_km_overlay(y, yrep[1:25, ], status_y = status_y) #> Note: `extrapolation_factor` now defaults to 1.2 (20%). #> To display all posterior predictive draws, set `extrapolation_factor = Inf`. ``` -------------------------------- ### Install bayesplot Development Version from GitHub Source: https://mc-stan.org/bayesplot/index.html Install the latest development version from GitHub. Ensure devtools is installed first. This installation does not include vignettes. ```r if (!require("devtools")) { install.packages("devtools") } devtools::install_github("stan-dev/bayesplot", dependencies = TRUE, build_vignettes = FALSE) ``` -------------------------------- ### Example: Recovering true values with stan_glm Source: https://mc-stan.org/bayesplot/reference/MCMC-recover.html Demonstrates fitting a model using rstanarm's stan_glm and then using mcmc_recover_intervals to check if the true parameter values are recovered. This example requires the rstanarm package. ```R # \dontrun{ library(rstanarm) alpha <- 1; beta <- rnorm(10, 0, 3); sigma <- 2 X <- matrix(rnorm(1000), 100, 10) y <- rnorm(100, mean = c(alpha + X %*% beta), sd = sigma) fit <- stan_glm(y ~ ., data = data.frame(y, X), refresh = 0) draws <- as.matrix(fit) print(colnames(draws)) #> [1] "(Intercept)" "X1" "X2" "X3" "X4" #> [6] "X5" "X6" "X7" "X8" "X9" #> [11] "X10" "sigma" true <- c(alpha, beta, sigma) mcmc_recover_intervals(draws, true) # put the coefficients on X into the same batch mcmc_recover_intervals(draws, true, batch = c(1, rep(2, 10), 1)) # equivalent mcmc_recover_intervals(draws, true, batch = grepl("X", colnames(draws))) ``` -------------------------------- ### Plot PPC Loo Pit Overlay Source: https://mc-stan.org/bayesplot/news/index.html The examples for `ppc_loo_pit_overlay()` have been corrected and now function as expected. ```R ppc_loo_pit_overlay(y_rep, y) ``` -------------------------------- ### Define and Run Example rstanarm Model Source: https://mc-stan.org/bayesplot/reference/tidy-params.html Defines an example binomial glmer model using rstanarm. This code is intended for execution on non-Windows systems or specific R architectures to avoid potential issues. ```R if (.Platform$OS.type != "windows" || .Platform$r_arch != "i386") { example_model <- stan_glmer(cbind(incidence, size - incidence) ~ size + period + (1|herd), data = lme4::cbpp, family = binomial, QR = TRUE, # this next line is only to keep the example small in size! chains = 2, cores = 1, seed = 12345, iter = 1000, refresh = 0) example_model } ``` -------------------------------- ### Install bayesplot from CRAN Source: https://mc-stan.org/bayesplot/index.html Use this command to install the stable version of the bayesplot package from CRAN. ```r install.packages("bayesplot") ``` -------------------------------- ### Example: PPC showing all posterior predictive draws Source: https://mc-stan.org/bayesplot/reference/PPC-censoring.html Demonstrates using ppc_km_overlay with extrapolation_factor set to Inf, which ensures all posterior predictive draws are displayed on the plot. ```R # With extrapolation_factor = Inf (show all posterior predictive draws) ppc_km_overlay(y, yrep[1:25, ], status_y = status_y, extrapolation_factor = Inf) ``` -------------------------------- ### Generate MCMC Draws for Demonstration Source: https://mc-stan.org/bayesplot/reference/MCMC-traces.html Generates example MCMC draws for use in demonstrating plotting functions. Shows dimensions and names of the resulting array. ```R x <- example_mcmc_draws(chains = 4, params = 6) dim(x) #> [1] 250 4 6 dimnames(x) #> $Iteration #> NULL #> #> $Chain #> [1] "chain:1" "chain:2" "chain:3" "chain:4" #> #> $Parameter #> [1] "alpha" "sigma" "beta[1]" "beta[2]" "beta[3]" "beta[4]" #> ``` -------------------------------- ### Load and Inspect rstanarm Model Source: https://mc-stan.org/bayesplot/reference/tidy-params.html Loads an example model from the rstanarm package and prints its summary. It then converts the posterior draws to a data frame for further analysis. ```R if (requireNamespace("rstanarm", quietly = TRUE)) { # see ?rstanarm::example_model fit <- example("example_model", package = "rstanarm", local=TRUE)$value print(fit) posterior <- as.data.frame(fit) str(posterior) ``` -------------------------------- ### Fit Stan Demo Model Source: https://mc-stan.org/bayesplot/reference/MCMC-parcoord.html Loads the `rstan` package and fits the 'eight_schools' demo model. Ensure `rstan` is installed and configured for your system. ```R library(rstan) fit <- stan_demo("eight_schools") ``` -------------------------------- ### Generate Example Data Vectors Source: https://mc-stan.org/bayesplot/reference/example-data.html Retrieves example data vectors for outcome (y), predictor (x), and group. Ensures data consistency for model fitting and visualization. The length of each vector is 434. ```R y <- example_y_data() x <- example_x_data() group <- example_group_data() length(y) ``` ```R tail(data.frame(y, x, group), 5) ``` -------------------------------- ### Create and arrange density overlay plots Source: https://mc-stan.org/bayesplot/reference/bayesplot_grid.html This example demonstrates creating two density overlay plots using different models and then arranging them side-by-side using bayesplot_grid. It shows how to enforce common axis limits and add custom subtitles. ```R library(rstanarm) mtcars$log_mpg <- log(mtcars$mpg) fit1 <- stan_glm(mpg ~ wt, data = mtcars, refresh = 0) fit2 <- stan_glm(log_mpg ~ wt, data = mtcars, refresh = 0) y <- mtcars$mpg yrep1 <- posterior_predict(fit1, draws = 50) yrep2 <- posterior_predict(fit2, fun = exp, draws = 50) color_scheme_set("blue") ppc1 <- ppc_dens_overlay(y, yrep1) ppc1 ppc1 + yaxis_text() color_scheme_set("red") ppc2 <- ppc_dens_overlay(y, yrep2) bayesplot_grid(ppc1, ppc2) # make sure the plots use the same limits for the axes bayesplot_grid(ppc1, ppc2, xlim = c(-5, 60), ylim = c(0, 0.2)) # remove the legends and add text bayesplot_grid(ppc1, ppc2, xlim = c(-5, 60), ylim = c(0, 0.2), legends = FALSE, subtitles = rep("Predicted MPG", 2)) ``` -------------------------------- ### Example: PPC with no extrapolation Source: https://mc-stan.org/bayesplot/reference/PPC-censoring.html Illustrates ppc_km_overlay with extrapolation_factor set to 1, meaning the plot will not extend beyond the largest observed value in y. ```R # With extrapolation_factor = 1 (no extrapolation) ppc_km_overlay(y, yrep[1:25, ], status_y = status_y, extrapolation_factor = 1) ``` -------------------------------- ### Set, Get, and View Color Schemes in bayesplot Source: https://mc-stan.org/bayesplot/reference/bayesplot-colors.html Demonstrates the basic usage of bayesplot color scheme functions. Use `color_scheme_set()` to change the active scheme, `color_scheme_get()` to retrieve colors, and `color_scheme_view()` to visualize schemes. ```R color_scheme_set("blue") color_scheme_view() ``` ```R color_scheme_get() #> blue #> 1 #d1e1ec #> 2 #b3cde0 #> 3 #6497b1 #> 4 #005b96 #> 5 #03396c #> 6 #011f4b ``` ```R color_scheme_get(i = c(3, 5)) # 3rd and 5th colors only #> $mid #> [1] "#6497b1" #> #> $dark #> [1] "#03396c" #> ``` ```R color_scheme_get("brightblue") #> brightblue #> 1 #cce5ff #> 2 #99cbff #> 3 #4ca5ff #> 4 #198bff #> 5 #0065cc #> 6 #004c99 ``` ```R color_scheme_view("brightblue") ``` ```R # compare multiple schemes color_scheme_view(c("pink", "gray", "teal")) ``` ```R color_scheme_view(c("viridis", "viridisA", "viridisB", "viridisC")) ``` -------------------------------- ### Create a sample 'foo' object Source: https://mc-stan.org/bayesplot/articles/graphical-ppcs.html Create a sample list with 'y' and 'yrep' components and assign it the class 'foo' to test the custom pp_check method. ```R x <- list(y = rnorm(200), yrep = matrix(rnorm(1e5), nrow = 500, ncol = 200)) class(x) <- "foo" ``` -------------------------------- ### Label Traceplot Starting After Warmup in bayesplot Source: https://mc-stan.org/bayesplot/news/index.html Use the `iter1` argument in `mcmc_trace()` to specify the starting iteration for the traceplot, useful for labeling after warmup. ```R mcmc_trace(..., iter1 = warmup_iterations) ``` -------------------------------- ### Apply dark theme and panel background using convenience function Source: https://mc-stan.org/bayesplot/reference/bayesplot_theme_get.html Shows an alternative to updating the theme directly by using the `panel_bg()` convenience function in conjunction with setting a dark theme. ```R bayesplot_theme_set(theme_dark()) mcmc_hist(x) + panel_bg(fill = "black") ``` -------------------------------- ### Basic PPC Intervals and Ribbons Source: https://mc-stan.org/bayesplot/reference/PPC-intervals.html Demonstrates the basic usage of ppc_intervals and ppc_ribbon with simulated data. Requires setting a color scheme. ```R y <- rnorm(50) yrep <- matrix(rnorm(5000, 0, 2), ncol = 50) color_scheme_set("brightblue") ppc_intervals(y, yrep) ppc_ribbon(y, yrep) ppc_ribbon(y, yrep, y_draw = "points") # \dontrun{ ppc_ribbon(y, yrep, y_draw = "both") # } ppc_intervals(y, yrep, size = 1.5, fatten = 0) # remove the yrep point estimates ``` -------------------------------- ### Create GitHub Repository Fork with usethis Source: https://mc-stan.org/bayesplot/CONTRIBUTING.html This function helps create a fork of the specified GitHub repository and clone it to your local machine. Recommended for new contributors. ```R usethis::create_from_github("stan-dev/bayesplot", fork = TRUE) ``` -------------------------------- ### Initialize Pull Request with usethis Source: https://mc-stan.org/bayesplot/CONTRIBUTING.html Use this function to initialize a Git branch for a pull request. Provide a brief description of the intended changes. ```R usethis::pr_init("brief-description-of-change") ``` -------------------------------- ### Get Available PPC Functions Source: https://mc-stan.org/bayesplot/reference/available_ppc.html Use `available_ppc` to get names of plotting functions. Pass arguments like `pattern`, `fixed`, `invert`, and `plots_only` to filter the results. Set `plots_only` to `FALSE` to include functions that return data. ```R available_ppc(pattern = NULL, fixed = FALSE, invert = FALSE, plots_only = TRUE) ``` ```R available_ppd(pattern = NULL, fixed = FALSE, invert = FALSE, plots_only = TRUE) ``` ```R available_mcmc( pattern = NULL, fixed = FALSE, invert = FALSE, plots_only = TRUE ) ``` -------------------------------- ### Set a new bayesplot theme and restore the old one Source: https://mc-stan.org/bayesplot/reference/bayesplot_theme_get.html Demonstrates how to set a new theme (e.g., `theme_minimal()`) and save the previous theme to restore it later. ```R old <- bayesplot_theme_set(theme_minimal()) mcmc_hist(x) bayesplot_theme_set(old) mcmc_hist(x) ``` -------------------------------- ### Get the current bayesplot theme Source: https://mc-stan.org/bayesplot/reference/bayesplot_theme_get.html Retrieves the currently active theme settings for bayesplots. ```APIDOC ## bayesplot_theme_get() ### Description Gets the current active bayesplot theme. ### Usage ``` bayesplot_theme_get() ``` ### Value Returns the current theme (a list of theme elements). ``` -------------------------------- ### Getting Color Schemes Source: https://mc-stan.org/bayesplot/reference/bayesplot-colors.html Retrieves the current or a specified color scheme. Can also retrieve specific colors from a scheme. ```APIDOC ## color_scheme_get() ### Description Retrieves hexadecimal color values for a specified or the current color scheme. ### Arguments - **scheme** (string, optional) - Name of the scheme to retrieve. If NULL, returns the current scheme. - **i** (integer vector, optional) - Subset of color indices (1-6) to return. ### Value Returns a list of hexadecimal color values. ### Example ```R color_scheme_get() color_scheme_get("brightblue") color_scheme_get(i = c(3, 5)) ``` ``` -------------------------------- ### Difference between ppd_dens_overlay and ppc_dens_overlay Source: https://mc-stan.org/bayesplot/reference/PPD-distributions.html Demonstrates the difference between plotting only predictive distributions (`ppd_dens_overlay`) and plotting predictive distributions alongside observed data (`ppc_dens_overlay`). ```R color_scheme_set("brightblue") preds <- example_yrep_draws() ppd_dens_overlay(ypred = preds[1:50, ]) ppc_dens_overlay(y = example_y_data(), yrep = preds[1:50, ]) ``` -------------------------------- ### Get Current bayesplot ggplot Theme Source: https://mc-stan.org/bayesplot/news/index.html Retrieve the current ggplot theme settings for bayesplot plots using `bayesplot_theme_get()`. ```R bayesplot_theme_get() ``` -------------------------------- ### Apply and Visualize Color Schemes with Plotting Functions Source: https://mc-stan.org/bayesplot/reference/bayesplot-colors.html Shows how to set a color scheme and then use it with bayesplot plotting functions like `mcmc_intervals` and `mcmc_areas`. Also demonstrates setting a scheme and then viewing it. ```R color_scheme_set("pink") x <- example_mcmc_draws() mcmc_intervals(x) ``` ```R color_scheme_set("teal") color_scheme_view() mcmc_intervals(x) ``` ```R color_scheme_set("red") mcmc_areas(x, regex_pars = "beta") ``` ```R color_scheme_set("purple") color_scheme_view() y <- example_y_data() yrep <- example_yrep_draws() ppc_stat(y, yrep, stat = "mean") + legend_none() #> Note: in most cases the default test statistic 'mean' is too weak to detect anything of interest. #> `stat_bin()` using `bins = 30`. Pick better value `binwidth`. ``` -------------------------------- ### Plot MCMC Autocorrelation Source: https://mc-stan.org/bayesplot/reference/MCMC-diagnostics.html Visualize the autocorrelation of MCMC draws for specified parameters. Requires example MCMC draws and setting a color scheme. ```R x <- example_mcmc_draws() color_scheme_set("green") mcmc_acf(x, pars = c("alpha", "beta[1]")) ``` -------------------------------- ### Get Data for Trace and Rank Plots Source: https://mc-stan.org/bayesplot/news/index.html Retrieve the data used for plotting trace plots and rank histograms by using the `mcmc_trace_data()` function. ```R data_for_plot <- mcmc_trace_data(fit) ``` -------------------------------- ### Define parameter selection with param_glue Source: https://mc-stan.org/bayesplot/reference/tidy-params.html The param_glue() function constructs parameter names using a pattern string with brace-enclosed expressions and named arguments for substitution. ```R param_glue("beta_{var}[{level}]", var = c("age", "income"), level = c(3,8)) ``` -------------------------------- ### example_x_data Source: https://mc-stan.org/bayesplot/reference/example-data.html Retrieves a numeric vector representing a predictor variable (X) for a basic linear regression model. ```APIDOC ## example_x_data ### Description Returns a numeric vector containing observations of one predictor variable `X` used in the example linear regression model. ### Usage ```R example_x_data() ``` ### Value A numeric vector with 434 observations. ``` -------------------------------- ### Get Default bayesplot Theme Source: https://mc-stan.org/bayesplot/reference/theme_default.html Returns the default ggplot theme used by bayesplot functions. It accepts base font size and family arguments. ```R theme_default( base_size = getOption("bayesplot.base_size", 12), base_family = getOption("bayesplot.base_family", "serif") ) ``` -------------------------------- ### Get Dimensions of Posterior Predictions Source: https://mc-stan.org/bayesplot/articles/graphical-ppcs.html Displays the dimensions of the posterior predictive distribution matrix. The first dimension is the number of draws, and the second is the number of observations. ```R dim(yrep_poisson) ``` ```R dim(yrep_nb) ``` -------------------------------- ### Comparing Parameterizations with Energy Plots Source: https://mc-stan.org/bayesplot/articles/visual-mcmc-diagnostics.html Compare centered and non-centered parameterizations using `mcmc_nuts_energy` with adjusted binwidth. This helps identify differences in chain exploration, especially when combined with `compare_cp_ncp`. ```R compare_cp_ncp( mcmc_nuts_energy(np_cp, binwidth = 1/2), mcmc_nuts_energy(np_ncp, binwidth = 1/2) ) ``` -------------------------------- ### Overlay Posterior Predictive Densities with ppc_dens_overlay Source: https://mc-stan.org/bayesplot/index.html Visualizes the distribution of observed data against simulated data from the posterior predictive distribution. Requires the fitted model object and posterior predictive draws. ```r color_scheme_set("red") ppc_dens_overlay(y = fit$y, yrep = posterior_predict(fit, draws = 50)) ``` -------------------------------- ### Get R-hat data Source: https://mc-stan.org/bayesplot/reference/MCMC-diagnostics.html Retrieves the data that would be used for plotting R-hat statistics, without generating the plot itself. Useful for custom visualizations or analysis. ```R mcmc_rhat_data(rhat, ...) ``` -------------------------------- ### Get Normalized Log Weights Source: https://mc-stan.org/bayesplot/reference/PPC-loo.html Obtains normalized log-weights from the PSIS object. These weights are used in various posterior predictive checks to account for the LOO approximation. ```R lw <- weights(psis1) # normalized log weights ``` -------------------------------- ### List All Available PPC Functions Source: https://mc-stan.org/bayesplot/reference/available_ppc.html Call `available_ppc()` without arguments to list all available PPC functions. This is useful for exploring the full range of PPC plotting and data-generating functions. ```R available_ppc(plots_only = FALSE) ``` -------------------------------- ### Set ColorBrewer Palettes in bayesplot Source: https://mc-stan.org/bayesplot/news/index.html Use ColorBrewer palettes as color schemes for bayesplot plots. For example, `color_scheme_set("brewer-Spectral")` applies the Spectral palette. ```R color_scheme_set("brewer-Spectral") ``` -------------------------------- ### Prepare Roach Data for Modeling Source: https://mc-stan.org/bayesplot/articles/graphical-ppcs.html Scale the 'roach1' variable by dividing by 100 to represent the pre-treatment number of roaches in hundreds. This is a common data preparation step before fitting regression models. ```r roaches$roach100 <- roaches$roach1 / 100 # pre-treatment number of roaches (in 100s) ``` -------------------------------- ### example_mcmc_draws Source: https://mc-stan.org/bayesplot/reference/example-data.html Generates MCMC draws from a posterior distribution for a basic linear regression model. Allows customization of the number of chains and parameters. ```APIDOC ## example_mcmc_draws ### Description Generates MCMC draws from the posterior distribution of parameters in a basic linear regression model. The number of chains and parameters can be specified. ### Usage ```R example_mcmc_draws(chains = 4, params = 4) ``` ### Arguments * `chains` (integer): An integer between 1 and 4 indicating the desired number of chains. * `params` (integer): An integer between 1 and 6 indicating the desired number of parameters. ### Value A numeric array or matrix containing MCMC draws. If `chains > 1`, returns a `250` (iterations) by `chains` by `params` array. If `chains = 1`, returns a `250` by `params` matrix. ### Details The returned object contains draws for `alpha` (intercept), `sigma` (error sd), and `beta[k]` (regression coefficients). The specific parameters included depend on the `params` argument. ``` -------------------------------- ### Get effective sample size ratio data Source: https://mc-stan.org/bayesplot/reference/MCMC-diagnostics.html Extracts the data for effective sample size to total sample size ratios, enabling custom plotting or analysis. ```R mcmc_neff_data(ratio, ...) ``` -------------------------------- ### Dot Plot for PPC Source: https://mc-stan.org/bayesplot/reference/PPC-distributions.html Displays a dot plot for the observed data and for each dataset (row) in `yrep`. Requires `ggdist::stat_dots` to be installed and `yrep` should contain a small number of rows. ```R # dot plot ppc_dots(y, yrep[1:8, ]) ``` -------------------------------- ### Select parameters with multiple expressions in braces Source: https://mc-stan.org/bayesplot/reference/tidy-params.html Use param_glue() with multiple expressions in braces to select parameters matching a more complex pattern. This allows for selecting parameters based on combinations of different categories or types. ```R posterior %>% select( param_glue( "r_condition[{level},{type}]", level = c("A", "B"), type = c("Intercept", "Slope")) ) %>% mcmc_hist() #> `stat_bin()` using `bins = 30`. Pick better value `binwidth`. ``` -------------------------------- ### Extracting PPC Data Source: https://mc-stan.org/bayesplot/reference/PPC-intervals.html Demonstrates how to extract the data frames used to generate PPC plots for further analysis or custom plotting. ```R # get the data frames used to make the ggplots ppc_dat <- ppc_intervals_data(y, yrep, x = year, prob = 0.5) ppc_group_dat <- ppc_intervals_data(y, yrep, x = year, group = group, prob = 0.5) ``` -------------------------------- ### Load R Packages for Plotting MCMC Draws Source: https://mc-stan.org/bayesplot/articles/plotting-mcmc-draws.html Load the necessary R packages: bayesplot for plotting, ggplot2 for customization, and rstanarm for fitting models. Ensure these packages are installed before running. ```r library("bayesplot") library("ggplot2") library("rstanarm") ``` -------------------------------- ### Plot MCMC Intervals with Parameter Exclusion Source: https://mc-stan.org/bayesplot/reference/tidy-params.html Resets the theme and color scheme, then plots MCMC intervals for parameters starting with 'b[' but excluding those ending in digits 7, 8, or 9. ```R bayesplot_theme_set() color_scheme_set("purple") not_789 <- vars(starts_with("b["), -matches("[7-9]")) mcmc_intervals(posterior, pars = not_789) ``` -------------------------------- ### Define Eight Schools Data in R Source: https://mc-stan.org/bayesplot/articles/visual-mcmc-diagnostics.html This R code defines the dataset for the eight schools example, including the number of schools (J), observed estimates (y), and standard errors (sigma). ```r schools_dat <- list( J = 8, y = c(28, 8, -3, 7, -1, 1, 18, 12), sigma = c(15, 10, 16, 11, 9, 11, 10, 18) ) ``` -------------------------------- ### Load Required Packages Source: https://mc-stan.org/bayesplot/articles/graphical-ppcs.html Load the bayesplot, ggplot2, and rstanarm packages for plotting and model fitting. ```r library("bayesplot") library("ggplot2") library("rstanarm") ``` -------------------------------- ### Overlaying Empirical Cumulative Distribution Functions (ECDF) for PPC Source: https://mc-stan.org/bayesplot/reference/PPC-distributions.html Use `ppc_ecdf_overlay` to compare the ECDF of observed data `y` with the ECDFs of posterior predictive simulations `yrep`. Use `ppc_ecdf_overlay_grouped` for grouped data. Set `discrete = TRUE` for discrete distributions. ```R ppc_ecdf_overlay( y, yrep, ..., discrete = FALSE, pad = TRUE, size = 0.25, alpha = 0.7 ) ``` ```R ppc_ecdf_overlay_grouped( y, yrep, group, ..., discrete = FALSE, pad = TRUE, size = 0.25, alpha = 0.7 ) ``` -------------------------------- ### Load Required R Packages Source: https://mc-stan.org/bayesplot/articles/visual-mcmc-diagnostics.html Load the bayesplot, ggplot2, and rstan packages for MCMC diagnostics and plotting. ggplot2 is useful for customizing plots, and rstan is used for fitting example models. ```r library("bayesplot") library("ggplot2") library("rstan") ``` -------------------------------- ### ppc_dens_overlay Source: https://mc-stan.org/bayesplot/reference/PPC-distributions.html Overlays density plots of observed data and replicated data. ```APIDOC ## ppc_dens_overlay ### Description Overlays density plots of observed data and replicated data. ### Usage ``` ppc_dens_overlay( y, yrep, ..., size = 0.25, alpha = 0.7, trim = FALSE, bw = "nrd0", adjust = 1, kernel = "gaussian", n_dens = 1024 ) ``` ### Parameters * `y`: Observed data. * `yrep`: Replicated data from the posterior predictive distribution. * `...`: Additional arguments passed to `density()`. * `size`: Size of the density lines. * `alpha`: Transparency of the density lines. * `trim`: Whether to trim the density plot. * `bw`: Bandwidth for density estimation. * `adjust`: Adjustment for bandwidth. * `kernel`: Kernel for density estimation. * `n_dens`: Number of points for density estimation. ``` -------------------------------- ### Filter PPD Functions by Pattern Source: https://mc-stan.org/bayesplot/reference/available_ppc.html Use `available_ppd()` with a pattern argument to filter the list of PPD (posterior predictive distribution) functions. This example lists PPD functions that end with '_data'. ```R available_ppd("_data", plots_only = FALSE) ``` -------------------------------- ### Select parameters by name and pattern Source: https://mc-stan.org/bayesplot/reference/tidy-params.html Use vars() with direct names or pattern matching functions like contains() to select parameters. Use negation with '-' to exclude parameters. ```R x <- example_mcmc_draws(params = 6) dimnames(x) #> $Iteration #> NULL #> #> $Chain #> [1] "chain:1" "chain:2" "chain:3" "chain:4" #> #> $Parameter #> [1] "alpha" "sigma" "beta[1]" "beta[2]" "beta[3]" "beta[4]" #> mcmc_hex(x, pars = vars(alpha, `beta[2]`)) ``` ```R mcmc_dens(x, pars = vars(sigma, contains("beta"))) ``` ```R mcmc_hist(x, pars = vars(-contains("beta"))) ``` -------------------------------- ### Extract Data for Parallel Coordinates Plot Source: https://mc-stan.org/bayesplot/reference/MCMC-parcoord.html Use 'mcmc_parcoord_data' to get the data in a tidy format suitable for plotting with other tools. It returns a tibble with draw, parameter, value, and divergence information. ```R d <- mcmc_parcoord_data(x, np = np) head(d) #> # A tibble: 6 × 4 #> Draw Parameter Value Divergent #> #> 1 1 alpha -14.1 0 #> 2 2 alpha -20.0 0 #> 3 3 alpha -21.0 0 #> 4 4 alpha -36.3 0 #> 5 5 alpha -7.58 0 #> 6 6 alpha -10.4 0 tail(d) #> # A tibble: 6 × 4 #> Draw Parameter Value Divergent #> #> 1 995 beta[3] 1.04 0 #> 2 996 beta[3] 1.07 0 #> 3 997 beta[3] 0.983 0 #> 4 998 beta[3] 0.821 0 #> 5 999 beta[3] 0.903 0 #> 6 1000 beta[3] 0.858 0 # } ``` -------------------------------- ### Plot MCMC Areas Ridges with Custom Theme and Color Scheme Source: https://mc-stan.org/bayesplot/reference/tidy-params.html Generates MCMC areas and ridges plots for parameters starting with 'b[' using a dark ggplot2 theme and a viridis color scheme. ```R bayesplot_theme_set(ggplot2::theme_dark()) color_scheme_set("viridisC") mcmc_areas_ridges(posterior, pars = vars(starts_with("b["))) ``` -------------------------------- ### Plot MCMC Intervals using param_glue() Helper Source: https://mc-stan.org/bayesplot/reference/tidy-params.html Illustrates using the param_glue() helper function to construct parameter names for plotting MCMC intervals, specifically targeting herd levels 1, 4, and 9. ```R just_149 <- vars(param_glue("b[(Intercept) herd:{level}]", level = c(1,4,9))) mcmc_intervals(posterior, pars = just_149) ``` -------------------------------- ### MCMC Intervals with Regex and General Transformation Source: https://mc-stan.org/bayesplot/reference/MCMC-intervals.html Applies a general transformation (e.g., 'exp') to all parameters matching a regex pattern. Useful for applying consistent transformations like exponentiation to multiple parameters. ```R mcmc_intervals(x, regex_pars = "beta", transformations = "exp") ``` -------------------------------- ### Get data for parallel coordinates plot Source: https://mc-stan.org/bayesplot/reference/MCMC-parcoord.html Retrieves the data that would be used to generate a parallel coordinates plot. Useful for custom plotting or analysis. Accepts various input formats for MCMC draws. ```R mcmc_parcoord_data( x, pars = character(), regex_pars = character(), transformations = list(), np = NULL ) ``` -------------------------------- ### Fitting Model for R-hat Diagnostics Source: https://mc-stan.org/bayesplot/articles/visual-mcmc-diagnostics.html Fit a Stan model with intentionally few iterations and dispersed initial values to generate high R-hat values for diagnostic purposes. This setup is useful for demonstrating R-hat visualization. ```R fit_cp_bad_rhat <- sampling(schools_mod_cp, data = schools_dat, iter = 50, init_r = 10, seed = 671254821) ``` -------------------------------- ### PPC with rstanarm and Custom Plotting Source: https://mc-stan.org/bayesplot/reference/PPC-intervals.html Shows PPC plots using data generated from an rstanarm model, including custom plot themes like background and grid lines. Requires the rstanarm package. ```R # \dontrun{ library("rstanarm") fit <- stan_glmer(mpg ~ wt + (1|cyl), data = mtcars, refresh = 0) yrep <- posterior_predict(fit) color_scheme_set("purple") ppc_intervals(y = mtcars$mpg, yrep = yrep, x = mtcars$wt, prob = 0.8) + panel_bg(fill="gray90", color = NA) + grid_lines(color = "white") ppc_ribbon(y = mtcars$mpg, yrep = yrep, x = mtcars$wt, prob = 0.6, prob_outer = 0.8) ppc_ribbon_grouped(y = mtcars$mpg, yrep = yrep, x = mtcars$wt, group = mtcars$cyl) color_scheme_set("gray") ppc_intervals(mtcars$mpg, yrep, prob = 0.5) + ggplot2::scale_x_continuous( labels = rownames(mtcars), breaks = 1:nrow(mtcars) ) + xaxis_text(angle = -70, vjust = 1, hjust = 0) + xaxis_title(FALSE) # } ``` -------------------------------- ### MCMC Areas Ridges for Hierarchical Parameters Source: https://mc-stan.org/bayesplot/reference/MCMC-intervals.html Plots hierarchically related MCMC parameters using ridgelines, suitable for visualizing complex models like the eight schools example. Requires `shinystan` posterior samples. ```R m <- shinystan::eight_schools@posterior_sample mcmc_areas_ridges(m, pars = "mu", regex_pars = "theta", border_size = 0.75) + ggtitle("Treatment effect on eight schools (Rubin, 1981)") ``` -------------------------------- ### Compare effective sample size ratios for different parameterizations Source: https://mc-stan.org/bayesplot/articles/visual-mcmc-diagnostics.html Compare effective sample size ratios for models with different parameterizations side-by-side using `mcmc_neff`. This helps assess the impact of parameterization on sampling efficiency. ```R neff_cp <- neff_ratio(fit_cp, pars = c("theta", "mu", "tau")) neff_ncp <- neff_ratio(fit_ncp, pars = c("theta", "mu", "tau")) compare_cp_ncp(mcmc_neff(neff_cp), mcmc_neff(neff_ncp), ncol = 1) ``` -------------------------------- ### Filter PPC Functions by Pattern Source: https://mc-stan.org/bayesplot/reference/available_ppc.html Use `available_ppc()` with a pattern argument to filter the list of PPC functions. This example shows how to list only PPC functions that end with '_data', which are typically used for generating data for custom plots. ```R available_ppc("_data", plots_only = FALSE) ``` -------------------------------- ### Apply dark theme and update panel background Source: https://mc-stan.org/bayesplot/reference/bayesplot_theme_get.html Applies a dark theme and then updates the panel background to black using `bayesplot_theme_update()`. This demonstrates combining theme settings. ```R color_scheme_set("brightblue") bayesplot_theme_set(theme_dark()) mcmc_hist(x) bayesplot_theme_update(panel.background = element_rect(fill = "black")) mcmc_hist(x) ``` -------------------------------- ### Basic Parallel Coordinates Plot Source: https://mc-stan.org/bayesplot/reference/MCMC-parcoord.html Generates a basic parallel coordinates plot from MCMC draws. Ensure the 'bayesplot' package is installed and loaded, and 'fit' is a valid Stan fit object. The 'draws' object should contain the parameters of interest. ```r draws <- as.array(fit, pars = c("mu", "tau", "theta", "lp__")) color_scheme_set("brightblue") mcmc_parcoord(draws, alpha = 0.05) ``` -------------------------------- ### List all available PPD functions Source: https://mc-stan.org/bayesplot/reference/available_ppc.html Use `available_ppd()` without arguments to retrieve a complete list of functions within the PPD (Posterior Predictive Distribution) module. This is helpful for exploring available PPD visualizations. ```R available_ppd() #> bayesplot PPD module: #> ppd_boxplot #> ppd_dens #> ppd_dens_overlay #> ppd_dots #> ppd_ecdf_overlay #> ppd_freqpoly #> ppd_freqpoly_grouped #> ppd_hist #> ppd_intervals #> ppd_intervals_grouped #> ppd_ribbon #> ppd_ribbon_grouped #> ppd_stat #> ppd_stat_2d #> ppd_stat_freqpoly #> ppd_stat_freqpoly_grouped #> ppd_stat_grouped ``` -------------------------------- ### Select parameters with one expression in braces Source: https://mc-stan.org/bayesplot/reference/tidy-params.html Use param_glue() with a single expression in braces to select parameters matching a specific pattern. This is useful for selecting a subset of related parameters. ```R library(dplyr) posterior <- tibble( b_Intercept = rnorm(1000), sd_condition__Intercept = rexp(1000), sigma = rexp(1000), `r_condition[A,Intercept]` = rnorm(1000), `r_condition[B,Intercept]` = rnorm(1000), `r_condition[C,Intercept]` = rnorm(1000), `r_condition[A,Slope]` = rnorm(1000), `r_condition[B,Slope]` = rnorm(1000) ) posterior %>% select( param_glue("r_condition[{level},Intercept]", level = c("A", "B")) ) %>% mcmc_hist() #> `stat_bin()` using `bins = 30`. Pick better value `binwidth`. ``` -------------------------------- ### Overlay Gaussian Distribution on MCMC Plot Source: https://mc-stan.org/bayesplot/reference/bayesplot-helpers.html Use `overlay_function` to superimpose a Gaussian distribution with the same mean and standard deviation as a posterior distribution onto an existing MCMC plot. Requires prior setup of MCMC draws and color schemes. ```R x <- example_mcmc_draws(chains = 4) dim(x) #> [1] 250 4 4 purple_gaussian <- overlay_function( fun = dnorm, args = list(mean(x[,, "beta[1]"]), sd(x[,, "beta[1]"])), color = "purple", linewidth = 2 ) color_scheme_set("gray") mcmc_hist(x, pars = "beta[1]", freq = FALSE) + purple_gaussian #> `stat_bin()` using `bins = 30`. Pick better value `binwidth`. # donttest { mcmc_dens(x, pars = "beta[1]") + purple_gaussian # } ``` -------------------------------- ### List PPC functions with '_grouped' pattern Source: https://mc-stan.org/bayesplot/articles/graphical-ppcs.html Use `available_ppc` with a pattern argument to filter and list PPC functions that include grouping capabilities. ```R available_ppc(pattern = "_grouped") ``` ```R bayesplot PPC module: (matching pattern '_grouped') ppc_bars_grouped ppc_dens_overlay_grouped ppc_ecdf_overlay_grouped ppc_error_hist_grouped ppc_error_scatter_avg_grouped ppc_freqpoly_grouped ppc_intervals_grouped ppc_km_overlay_grouped ppc_pit_ecdf_grouped ppc_ribbon_grouped ppc_scatter_avg_grouped ppc_stat_freqpoly_grouped ppc_stat_grouped ppc_violin_grouped ``` -------------------------------- ### Filter MCMC Functions by Pattern Source: https://mc-stan.org/bayesplot/reference/available_ppc.html Use `available_mcmc()` with a pattern argument to filter the list of MCMC (Markov Chain Monte Carlo) functions. This example lists MCMC functions that end with '_data', often used for extracting MCMC-related data. ```R available_mcmc("_data", plots_only = FALSE) ``` -------------------------------- ### Overlay Density Plots for PPC Source: https://mc-stan.org/bayesplot/articles/graphical-ppcs.html Creates an overlay of density estimates comparing the observed data 'y' with a subset of posterior predictive replications. Useful for assessing how well the model captures the overall distribution of the data. ```R color_scheme_set("brightblue") ppc_dens_overlay(y, yrep_poisson[1:50, ]) ``` -------------------------------- ### Get, set, and update bayesplot themes Source: https://mc-stan.org/bayesplot/reference/bayesplot_theme_get.html Use `bayesplot_theme_get()` to retrieve the current theme, `bayesplot_theme_set()` to apply a new theme, and `bayesplot_theme_update()` or `bayesplot_theme_replace()` to modify individual theme elements. These functions are analogous to ggplot2's theme management functions. ```R bayesplot_theme_get() bayesplot_theme_set(new = theme_default()) bayesplot_theme_update(...) bayesplot_theme_replace(...) ``` -------------------------------- ### Trace Plots with mcmc_trace Source: https://mc-stan.org/bayesplot/index.html Generates trace plots for MCMC chains, useful for diagnosing convergence. Allows specifying parameters and warmup iterations. Uses faceting for multiple parameters. ```r # with rstan demo model library("rstan") fit2 <- stan_demo("eight_schools", warmup = 300, iter = 700) posterior2 <- extract(fit2, inc_warmup = TRUE, permuted = FALSE) color_scheme_set("mix-blue-pink") p <- mcmc_trace(posterior2, pars = c("mu", "tau"), n_warmup = 300, facet_args = list(nrow = 2, labeller = label_parsed)) p + facet_text(size = 15) ``` -------------------------------- ### Fit Bayesian Model with rstanarm Source: https://mc-stan.org/bayesplot/reference/PPC-loo.html Fits a linear mixed-effects model to radon data using stan_lmer. Ensure rstanarm and loo are installed and loaded. The model includes fixed and random effects. Note the warnings about chain mixing and effective sample size, suggesting more iterations might be needed. ```R library(rstanarm) library(loo) fit <- stan_lmer( log_radon ~ floor + log_uranium + floor:log_uranium + (1 + floor | county), data = radon, iter = 100, chains = 2, cores = 2 ) ``` -------------------------------- ### List all available MCMC functions Source: https://mc-stan.org/bayesplot/reference/available_ppc.html Call `available_mcmc()` with no arguments to list all functions in the MCMC module. This is useful for discovering available plotting options. ```R available_mcmc() #> bayesplot MCMC module: #> mcmc_acf #> mcmc_acf_bar #> mcmc_areas #> mcmc_areas_ridges #> mcmc_combo #> mcmc_dens #> mcmc_dens_chains #> mcmc_dens_overlay #> mcmc_hex #> mcmc_hist #> mcmc_hist_by_chain #> mcmc_intervals #> mcmc_neff #> mcmc_neff_hist #> mcmc_nuts_acceptance #> mcmc_nuts_divergence #> mcmc_nuts_energy #> mcmc_nuts_stepsize #> mcmc_nuts_treedepth #> mcmc_pairs #> mcmc_parcoord #> mcmc_rank_ecdf #> mcmc_rank_hist #> mcmc_rank_overlay #> mcmc_recover_hist #> mcmc_recover_intervals #> mcmc_recover_scatter #> mcmc_rhat #> mcmc_rhat_hist #> mcmc_scatter #> mcmc_trace #> mcmc_trace_highlight #> mcmc_violin ``` -------------------------------- ### Density Plot (Wizard Hat) for PPC Source: https://mc-stan.org/bayesplot/reference/PPC-distributions.html Generates a smoothed kernel density estimate plot for the observed data and a small subset of posterior predictive draws. Useful for visualizing distributions. ```R # wizard hat plot color_scheme_set("blue") ppc_dens(y, yrep[200:202, ]) ```