### Install bayesplot Package Source: https://context7.com/stan-dev/bayesplot/llms.txt Install the stable version from CRAN or the development version from GitHub. ```r install.packages("bayesplot") ``` ```r devtools::install_github("stan-dev/bayesplot", dependencies = TRUE, build_vignettes = FALSE) ``` -------------------------------- ### Install bayesplot Development Version from GitHub Source: https://github.com/stan-dev/bayesplot/blob/master/README.md Install the latest development version of bayesplot directly from GitHub. This requires the devtools package and may not include vignettes by default. ```r if (!require("devtools")) { install.packages("devtools") } devtools::install_github("stan-dev/bayesplot", dependencies = TRUE, build_vignettes = FALSE) ``` -------------------------------- ### Install bayesplot from CRAN Source: https://github.com/stan-dev/bayesplot/blob/master/README.md Use this command to install the stable version of the bayesplot package from the Comprehensive R Archive Network (CRAN). ```r install.packages("bayesplot") ``` -------------------------------- ### Extract data for PPC plots Source: https://github.com/stan-dev/bayesplot/blob/master/NEWS.md New functions ending in `_data` return data prepared for plotting, without generating the plot itself. Examples include `ppc_intervals_data()`, `ppc_ribbon_data()`, `mcmc_parcoord_data()`, `mcmc_rhat_data()`, and `mcmc_neff_data()`. ```R ppc_intervals_data(y, y_rep) ppc_ribbon_data(y, y_rep) mcmc_parcoord_data(fit) mcmc_rhat_data(fit) mcmc_neff_data(fit) ``` -------------------------------- ### Get data for PPC plots Source: https://github.com/stan-dev/bayesplot/blob/master/NEWS.md The `ppc_data()` function returns the data prepared for plotting by many PPC functions, useful for custom visualizations. ```R ppc_data(y, y_rep, train_indices = "all") ``` -------------------------------- ### Grouped Posterior Predictive Checks with bayesplot Source: https://github.com/stan-dev/bayesplot/blob/master/README.md Performs grouped posterior predictive checks using ppc_stat_grouped, calculating a specified statistic (e.g., median) for the observed data and simulated data within defined groups. This example demonstrates piping for a more concise workflow. ```r # also works nicely with piping library("dplyr") color_scheme_set("brightblue") fit %>% posterior_predict(draws = 500) %>% ppc_stat_grouped(y = mtcars$mpg, group = mtcars$carb, stat = "median") ``` -------------------------------- ### Overlay Posterior Predictive Densities with bayesplot Source: https://github.com/stan-dev/bayesplot/blob/master/README.md Visualizes the distribution of actual data against simulated data from the posterior predictive distribution using ppc_dens_overlay. Requires setting a color scheme and obtaining posterior predictions. ```r color_scheme_set("red") ppc_dens_overlay(y = fit$y, yrep = posterior_predict(fit, draws = 50)) ``` -------------------------------- ### MCMC Intervals Colored by R-hat Source: https://context7.com/stan-dev/bayesplot/llms.txt Illustrates coloring `mcmc_intervals()` plots by R-hat values. This helps identify parameters with potential convergence issues. ```R fake_rhat <- c(1.0, 1.07, 1.3, 1.01, 1.15, 1.005) color_scheme_set("blue") mcmc_intervals(x, rhat = fake_rhat) ``` -------------------------------- ### Visualize posterior density with ridgelines Source: https://github.com/stan-dev/bayesplot/blob/master/NEWS.md New functions `mcmc_dens_chains()` and `mcmc_areas_ridges()` visualize posterior density using ridgelines, suitable for hierarchical models. ```R mcmc_dens_chains(fit, pars = "beta[1]") mcmc_areas_ridges(fit, pars = "beta[1]") ``` -------------------------------- ### Test Package as CRAN Source: https://github.com/stan-dev/bayesplot/wiki/bayesplot-development-notes Set environment variable to simulate CRAN testing conditions and run package tests. ```R Sys.setenv(NOT_CRAN = "false") devtools::test() ``` -------------------------------- ### LOO PIT predictive check Source: https://github.com/stan-dev/bayesplot/blob/master/NEWS.md The `ppc_loo_pit_overlay()` function provides an improved visualization for LOO PIT predictive checks. ```R ppc_loo_pit_overlay(y, y_rep) ``` -------------------------------- ### Handle discrete data in ppc_ecdf_overlay Source: https://github.com/stan-dev/bayesplot/blob/master/NEWS.md The `discrete` argument in `ppc_ecdf_overlay()` can be set to TRUE to make the geom more appropriate for discrete data. ```R ppc_ecdf_overlay(y, y_rep, discrete = TRUE) ``` -------------------------------- ### MCMC Histograms by Chain Source: https://context7.com/stan-dev/bayesplot/llms.txt Creates per-chain histograms using a facet grid. Useful for visualizing the distribution of draws for a specific parameter across different chains. ```R color_scheme_set("orange") mcmc_hist_by_chain(x, regex_pars = "beta") ``` -------------------------------- ### MCMC Interval Plots Source: https://context7.com/stan-dev/bayesplot/llms.txt Visualizes quantile-based credible intervals using `mcmc_intervals()`. Supports customization of interval widths, point estimates, and coloring by R-hat. ```R library(bayesplot) library(ggplot2) x <- example_mcmc_draws(params = 6) color_scheme_set("brightblue") mcmc_intervals(x) ``` ```R mcmc_intervals(x, pars = c("beta[1]", "beta[2]"), prob = 0.8, prob_outer = 0.95, point_est = "mean") ``` -------------------------------- ### MCMC Trace Plots Source: https://context7.com/stan-dev/bayesplot/llms.txt Generates standard or highlight-chain trace plots of MCMC draws over iterations. Useful for visualizing MCMC convergence and behavior. ```APIDOC ## MCMC Trace Plots ### `mcmc_trace()` / `mcmc_trace_highlight()` Standard or highlight-chain trace plots of MCMC draws over iterations. Accepts a 3-D array `[iterations × chains × parameters]`, a list of matrices, or a data frame. The `n_warmup` argument shades warmup iterations gray. NUTS divergences can be annotated as rug marks via the `np` argument (from `nuts_params()`). ```r library(bayesplot) library(ggplot2) x <- example_mcmc_draws(chains = 4, params = 6) # Basic trace plot for parameters matching "beta" color_scheme_set("viridis") mcmc_trace(x, regex_pars = "beta") # Zoom to iterations 100–130, shade warmup, annotate divergences # (with a real Stan fit, pass nuts_params(fit) to 'np') color_scheme_set("mix-blue-red") mcmc_trace( x, pars = c("alpha", "sigma"), n_warmup = 100, window = c(100, 130), size = 0.8 ) + panel_bg(fill = "gray95", color = NA) + legend_move("top") # Highlight a single chain (chain 2 is opaque; others are faded) color_scheme_set("brightblue") mcmc_trace_highlight(x, pars = "sigma", highlight = 2, size = 2) ``` ``` -------------------------------- ### Compare Observed Data vs. Posterior Predictive Distributions Source: https://context7.com/stan-dev/bayesplot/llms.txt Use these functions to compare the distribution of observed data `y` against replications `yrep` drawn from the posterior predictive distribution. `yrep` should be a matrix with one row per posterior draw and one column per observation. Ensure `bayesplot` and `ggplot2` are loaded. ```r library(bayesplot) library(ggplot2) y <- example_y_data() # observed outcome vector (length N) yrep <- example_yrep_draws() # S × N matrix of posterior predictive draws group <- example_group_data() # Overlaid density curves: 25 yrep draws (light) + y (dark) color_scheme_set("brightblue") ppc_dens_overlay(y, yrep[1:25, ]) # ECDF overlay: step functions for yrep, darker step for y ppc_ecdf_overlay(y, yrep[sample(nrow(yrep), 25), ]) # Histograms: one facet per yrep draw + one for y color_scheme_set("red") ppc_hist(y, yrep[1:8, ]) # Box plots with notches ppc_boxplot(y, yrep[1:8, ]) # Density and ECDF overlays faceted by group color_scheme_set("teal") ppc_dens_overlay_grouped(y, yrep[1:25, ], group = group) ppc_ecdf_overlay_grouped(y, yrep[1:25, ], group = group) # Violin grouped: yrep as violin, y overlaid as outline or points color_scheme_set("gray") ppc_violin_grouped(y, yrep, group, size = 1.5) ppc_violin_grouped(y, yrep, group, alpha = 0, y_draw = "both", y_size = 1.5, y_alpha = 0.5, y_jitter = 0.33) # PIT-ECDF: probability integral transform check with 99% bands ppc_pit_ecdf(y, yrep, prob = 0.99, plot_diff = FALSE) ppc_pit_ecdf(y, yrep, prob = 0.99, plot_diff = TRUE) # difference plot ``` -------------------------------- ### MCMC Effective Sample Size Ratio Histogram Source: https://context7.com/stan-dev/bayesplot/llms.txt Displays the effective sample size (N_eff) to total sample size (N) ratio as a histogram using `mcmc_neff_hist()`. Summarizes the distribution of these ratios. ```R mcmc_neff_hist(neff_vals) ``` -------------------------------- ### MCMC Distribution Plots Source: https://context7.com/stan-dev/bayesplot/llms.txt Visualizes marginal posterior distributions of MCMC draws using histograms, density plots, violin plots, and quantile dot plots. ```APIDOC ## MCMC Distribution Plots ### `mcmc_hist()` / `mcmc_dens()` / `mcmc_dens_overlay()` / `mcmc_violin()` / `mcmc_dots()` Marginal distribution summaries of posterior draws with all chains merged or separated. `mcmc_dens_overlay()` draws one density curve per chain; `mcmc_dens_chains()` uses ridgelines. `mcmc_violin()` shows chain-specific violins. `mcmc_dots()` / `mcmc_dots_by_chain()` produce quantile dot plots (requires **ggdist**). ```r library(bayesplot) x <- example_mcmc_draws(chains = 4, params = 6) ``` -------------------------------- ### Plot Posterior Distributions with bayesplot Source: https://github.com/stan-dev/bayesplot/blob/master/README.md Generates a plot of posterior distributions for specified parameters using mcmc_areas. Requires loading bayesplot, rstanarm, and ggplot2 libraries, and fitting a model with stan_glm. ```r library("bayesplot") library("rstanarm") library("ggplot2") fit <- stan_glm(mpg ~ ., data = mtcars) posterior <- as.matrix(fit) plot_title <- ggtitle("Posterior distributions", "with medians and 80% intervals") mcmc_areas(posterior, pars = c("cyl", "drat", "am", "wt"), prob = 0.8) + plot_title ``` -------------------------------- ### MCMC Histograms Source: https://context7.com/stan-dev/bayesplot/llms.txt Generates histograms of MCMC draws for parameters. Supports free x-axis scales per facet and named transformation strings for labeling axes. ```R color_scheme_set("brightblue") mcmc_hist(x) ``` ```R mcmc_hist( x, pars = c("beta[1]", "beta[2]", "sigma"), transformations = list(sigma = "log") ) ``` -------------------------------- ### MCMC Density Overlay Source: https://context7.com/stan-dev/bayesplot/llms.txt Plots overlaid per-chain density curves. Allows for comparison of density estimates across chains for selected parameters. ```R color_scheme_set("mix-teal-pink") mcmc_dens_overlay(x, pars = c("sigma", "beta[2]"), facet_args = list(nrow = 2)) ``` -------------------------------- ### Configure Knitr Chunk Options Source: https://github.com/stan-dev/bayesplot/blob/master/vignettes/children/SETTINGS-knitr.txt Sets default options for all R code chunks processed by Knitr. This ensures consistent figure generation for bayesplot visualizations. ```r stopifnot(require("knitr")) library("bayesplot") knitr::opts_chunk$set( dev = "png", dpi = 150, fig.asp = 0.618, fig.width = 5, out.width = "60%", fig.align = "center", comment = NA, eval = if (isTRUE(exists("params"))) params$EVAL else FALSE ) ``` -------------------------------- ### MCMC Trace Plot Source: https://context7.com/stan-dev/bayesplot/llms.txt Generate standard or highlight-chain trace plots for MCMC draws. The n_warmup argument shades warmup iterations, and the np argument can annotate divergences. Plots can be customized with ggplot2 functions. ```r library(bayesplot) library(ggplot2) x <- example_mcmc_draws(chains = 4, params = 6) # Basic trace plot for parameters matching "beta" color_scheme_set("viridis") mcmc_trace(x, regex_pars = "beta") # Zoom to iterations 100–130, shade warmup, annotate divergences # (with a real Stan fit, pass nuts_params(fit) to 'np') color_scheme_set("mix-blue-red") mcmc_trace( x, pars = c("alpha", "sigma"), n_warmup = 100, window = c(100, 130), size = 0.8 ) + panel_bg(fill = "gray95", color = NA) + legend_move("top") # Highlight a single chain (chain 2 is opaque; others are faded) color_scheme_set("brightblue") mcmc_trace_highlight(x, pars = "sigma", highlight = 2, size = 2) ``` -------------------------------- ### MCMC Trace Plot with RStan Source: https://github.com/stan-dev/bayesplot/blob/master/README.md Generates an MCMC trace plot for specified parameters ('mu', 'tau') from an RStan fit. Requires the 'rstan' library and a fitted model object. Customizes plot appearance with color schemes and facet labels. ```r 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) ``` -------------------------------- ### MCMC Violin Plot Source: https://context7.com/stan-dev/bayesplot/llms.txt Creates violin plots for MCMC draws, showing the distribution of draws for each chain. Includes options for adding panel backgrounds and styling. ```R color_scheme_set("green") mcmc_violin(x) + panel_bg(color = "gray20", linewidth = 2, fill = "gray30") ``` -------------------------------- ### Compare Posterior Predictive Test Statistics to Observed Values Source: https://context7.com/stan-dev/bayesplot/llms.txt Use these functions to display the distribution of a test statistic `T(yrep)` across posterior predictive replications and compare it to the observed value `T(y)`. Any scalar-valued function can be used as the statistic. Ensure `bayesplot` is loaded. ```r library(bayesplot) y <- example_y_data() yrep <- example_yrep_draws() group <- example_group_data() # Distribution of the median across yrep; vertical line at median(y) color_scheme_set("brightblue") ppc_stat(y, yrep, stat = "median") ppc_stat(y, yrep, stat = "sd") + legend_none() # Custom statistic: 25th percentile q25 <- function(y) quantile(y, 0.25) ppc_stat(y, yrep, stat = "q25") # Grouped test statistic — one facet per group level color_scheme_set("teal") ppc_stat_grouped(y, yrep, group, stat = "median") ppc_stat_grouped(y, yrep, group, stat = "mad") + yaxis_text() # 2D scatterplot of two test statistics across yrep ppc_stat_2d(y, yrep, stat = c("mean", "sd")) # Discrete data example set.seed(42) y_disc <- rbinom(30, size = 1, prob = 0.3) yrep_disc <- matrix(rbinom(3000, size = 1, prob = 0.5), nrow = 100) ppc_stat(y_disc, yrep_disc, stat = "mean", discrete = TRUE) ``` -------------------------------- ### Return data from mcmc_intervals and mcmc_areas Source: https://github.com/stan-dev/bayesplot/blob/master/NEWS.md New functions `mcmc_intervals_data()` and `mcmc_areas_data()` return the data plotted by `mcmc_intervals()` and `mcmc_areas()`, respectively. ```R mcmc_intervals_data(fit) mcmc_areas_data(fit) ``` -------------------------------- ### MCMC R-hat Lollipop Plot Source: https://context7.com/stan-dev/bayesplot/llms.txt Visualizes R-hat values using `mcmc_rhat()`. Parameters are plotted with lollipop segments, colored by R-hat quality (light/mid/dark). ```R library(bayesplot) rhat_vals <- c(runif(80, 1.0, 1.05), runif(15, 1.05, 1.1), runif(5, 1.1, 1.3)) names(rhat_vals) <- paste0("param_", seq_along(rhat_vals)) color_scheme_set("blue") mcmc_rhat(rhat_vals) ``` -------------------------------- ### MCMC R-hat Histogram Source: https://context7.com/stan-dev/bayesplot/llms.txt Displays R-hat values as a histogram using `mcmc_rhat_hist()`. Provides a summary view of the distribution of R-hat statistics. ```R mcmc_rhat_hist(rhat_vals) ``` -------------------------------- ### MCMC Dot Plot Source: https://context7.com/stan-dev/bayesplot/llms.txt Generates a quantile dot plot, which requires the ggdist package. Useful for visualizing quantiles of posterior distributions for selected parameters. ```R color_scheme_set("pink") mcmc_dots(x, pars = c("alpha", "beta[2]")) ``` -------------------------------- ### MCMC Scatterplot Source: https://context7.com/stan-dev/bayesplot/llms.txt Creates scatterplots of two parameters from MCMC draws using `mcmc_scatter()`. Supports highlighting divergences and customizing plot aesthetics. ```R library(bayesplot) library(ggplot2) x <- example_mcmc_draws(chains = 4, params = 6) color_scheme_set("darkgray") mcmc_scatter( as.matrix(x), pars = c("alpha", "beta[1]"), size = 1, alpha = 0.5 ) ``` -------------------------------- ### MCMC Scatter Plot with Divergences Source: https://github.com/stan-dev/bayesplot/blob/master/README.md Creates an MCMC scatter plot showing the relationship between two parameters ('tau', 'theta[1]') and highlighting divergent transitions. Uses 'nuts_params' to extract NUTS parameters and customizes the style for divergent points. ```r color_scheme_set("darkgray") mcmc_scatter( as.matrix(fit2), pars = c("tau", "theta[1]"), np = nuts_params(fit2), np_style = scatter_style_np(div_color = "green", div_alpha = 0.8) ) ``` -------------------------------- ### Control faceting in grouped PPC plots Source: https://github.com/stan-dev/bayesplot/blob/master/NEWS.md The `facet_args` argument in `ppc_stat_grouped()` and `ppc_stat_freqpoly_grouped()` allows control over ggplot2 faceting. ```R ppc_stat_grouped(y, y_rep, group = group_var, facet_args = list(nrow = 2)) ``` -------------------------------- ### MCMC Pairwise Scatterplot Matrix Source: https://context7.com/stan-dev/bayesplot/llms.txt Generates a pairwise scatterplot matrix using `mcmc_pairs()`. Useful for visualizing relationships between multiple parameters. ```R color_scheme_set("blue") mcmc_pairs( x, pars = c("alpha", "sigma", "beta[1]"), off_diag_args = list(size = 0.5, alpha = 0.4) ) ``` -------------------------------- ### NUTS Acceptance Rate Plot Source: https://context7.com/stan-dev/bayesplot/llms.txt Visualizes the NUTS (No-U-Turn Sampler) acceptance rate. Requires `nuts_params()` output from a Stan fit. ```R library(bayesplot) library(ggplot2) # Requires a Stan fit; shown here with rstanarm # library(rstanarm) ``` -------------------------------- ### MCMC Distribution Plots Source: https://context7.com/stan-dev/bayesplot/llms.txt Summarize marginal posterior distributions of MCMC draws. Functions include histograms (mcmc_hist), density plots (mcmc_dens, mcmc_dens_overlay, mcmc_dens_chains), violin plots (mcmc_violin), and quantile dot plots (mcmc_dots, mcmc_dots_by_chain). ```r library(bayesplot) x <- example_mcmc_draws(chains = 4, params = 6) ``` -------------------------------- ### Theme Management Source: https://context7.com/stan-dev/bayesplot/llms.txt Functions to manage the ggplot2 theme applied to bayesplot plots. Includes setting defaults, updating elements, and restoring original themes. ```APIDOC ## Theme Management Functions ### `theme_default()` / `bayesplot_theme_set()` / `bayesplot_theme_update()` **Description:** Manage the ggplot2 theme applied to all bayesplot plots. The default is `theme_default()`, a clean bw-based theme. Theme changes affect only bayesplots, not other ggplot objects. ### Usage: ```r # Set to built-in default theme bayesplot_theme_set() # Set with custom ggplot2 theme bayesplot_theme_set(theme_default(base_size = 9, base_family = "sans")) bayesplot_theme_set(theme_classic()) # Update individual theme elements bayesplot_theme_update( plot.title = element_text(size = 16, face = "bold"), panel.background = element_rect(fill = "gray98") ) # Restore the default theme bayesplot_theme_set() ``` ``` -------------------------------- ### NUTS Energy Diagnostic Plot Source: https://github.com/stan-dev/bayesplot/blob/master/README.md Visualizes the NUTS energy diagnostic using the 'mcmc_nuts_energy' function. This plot helps assess the efficiency of the Hamiltonian Monte Carlo sampler. Requires NUTS parameters extracted from a fitted model. ```r color_scheme_set("red") np <- nuts_params(fit2) mcmc_nuts_energy(np) + ggtitle("NUTS Energy Diagnostic") ``` -------------------------------- ### MCMC Effective Sample Size Ratio Lollipop Plot Source: https://context7.com/stan-dev/bayesplot/llms.txt Visualizes the effective sample size (N_eff) to total sample size (N) ratio using `mcmc_neff()`. Parameters are plotted with lollipop segments, colored by ratio (high/ok/low). ```R neff_vals <- c(runif(70, 0.5, 1.0), runif(20, 0.1, 0.5), runif(10, 0.0, 0.1)) color_scheme_set("purple") mcmc_neff(neff_vals, size = 3) ``` -------------------------------- ### MCMC Rank Plots Source: https://context7.com/stan-dev/bayesplot/llms.txt Provides rank-based chain-mixing diagnostics, including rank histograms, overlaid rank step-lines, and empirical cumulative distribution functions (ECDFs). ```APIDOC ## MCMC Rank Plots ### `mcmc_rank_hist()` / `mcmc_rank_overlay()` / `mcmc_rank_ecdf()` Rank-based chain-mixing diagnostics. Instead of raw values over iterations, ranks of the combined draws are histogrammed per chain. A uniform distribution across chains indicates good mixing. `mcmc_rank_ecdf()` adds simultaneous confidence bands. ```r x <- example_mcmc_draws(chains = 4, params = 6) color_scheme_set("viridisE") # Rank histogram — one panel per (parameter × chain) mcmc_rank_hist(x, pars = c("alpha", "sigma"), ref_line = TRUE) # Overlaid rank step-lines — all chains on one panel per parameter mcmc_rank_overlay(x, regex_pars = "beta", ref_line = TRUE) # Rank ECDF with 99% simultaneous confidence bands mcmc_rank_ecdf(x, prob = 0.99) # ECDF difference plot: deviations from the ideal uniform distribution mcmc_rank_ecdf(x, prob = 0.99, plot_diff = TRUE) ``` ``` -------------------------------- ### Posterior Predictive Intervals with RStanarm Source: https://github.com/stan-dev/bayesplot/blob/master/README.md Generates posterior predictive intervals for a regression model fitted with 'stan_glmer' from the 'rstanarm' package. Visualizes observed data against predicted intervals, with custom panel backgrounds and grid lines. ```r color_scheme_set("purple") fit <- stan_glmer(mpg ~ wt + (1|cyl), data = mtcars) ppc_intervals( y = mtcars$mpg, yrep = posterior_predict(fit), x = mtcars$wt, prob = 0.5 ) + labs( x = "Weight (1000 lbs)", y = "MPG", title = "50% posterior predictive intervals \nvs observed miles per gallon", subtitle = "by vehicle weight" ) + panel_bg(fill = "gray95", color = NA) + grid_lines(color = "white") ``` -------------------------------- ### Set and View Color Schemes Source: https://context7.com/stan-dev/bayesplot/llms.txt Manage the global color palette for bayesplot functions. Supports preset schemes, custom hex values, and mixed schemes. Use color_scheme_view() to visualize the current or multiple schemes. ```r library(bayesplot) library(ggplot2) # Set a preset scheme color_scheme_set("viridis") # View the current scheme as a color swatch color_scheme_view() # Retrieve specific colors (indices 1–6 = lightest to darkest) color_scheme_get(i = c(1, 3, 6)) # Compare multiple schemes side-by-side color_scheme_view(c("pink", "teal", "viridisA")) # Custom six-color scheme (light → dark) orange_scheme <- c("#ffebcc", "#ffcc80", "#ffad33", "#e68a00", "#995c00", "#663d00") color_scheme_set(orange_scheme) color_scheme_view() # Mix two preset schemes color_scheme_set("mix-blue-pink") x <- example_mcmc_draws(chains = 4, params = 6) mcmc_hist(x, regex_pars = "beta") ``` -------------------------------- ### Color Scheme Management Source: https://context7.com/stan-dev/bayesplot/llms.txt Functions to set, retrieve, and visualize the global color palette used by bayesplot functions. Supports preset schemes and custom color definitions. ```APIDOC ## Color Scheme Management ### `color_scheme_set()` / `color_scheme_get()` / `color_scheme_view()` Set, retrieve, or visualize the global color palette used by all bayesplot functions. Preset schemes include `"blue"`, `"brightblue"`, `"red"`, `"green"`, `"teal"`, `"pink"`, `"purple"`, `"gray"`, `"darkgray"`, `"yellow"`, `"viridis"` (and variants A–E), mix combos (`"mix-teal-pink"`), and ColorBrewer palettes (`"brewer-Blues"`). A custom scheme is specified as exactly six hex/color values from lightest to darkest. ```r library(bayesplot) library(ggplot2) # Set a preset scheme color_scheme_set("viridis") # View the current scheme as a color swatch color_scheme_view() # Retrieve specific colors (indices 1–6 = lightest to darkest) color_scheme_get(i = c(1, 3, 6)) # Compare multiple schemes side-by-side color_scheme_view(c("pink", "teal", "viridisA")) # Custom six-color scheme (light → dark) orange_scheme <- c("#ffebcc", "#ffcc80", "#ffad33", "#e68a00", "#995c00", "#663d00") color_scheme_set(orange_scheme) color_scheme_view() # Mix two preset schemes color_scheme_set("mix-blue-pink") x <- example_mcmc_draws(chains = 4, params = 6) mcmc_hist(x, regex_pars = "beta") ``` ``` -------------------------------- ### MCMC Ridgeline Densities Source: https://context7.com/stan-dev/bayesplot/llms.txt Generates ridgeline plots where parameters are on the y-axis and chains are represented as overlapping lines. Provides a compact display of density distributions. ```R color_scheme_set("purple") mcmc_dens_chains(x, pars = c("beta[1]", "beta[2]", "beta[3]")) ``` -------------------------------- ### MCMC Rank Plots Source: https://context7.com/stan-dev/bayesplot/llms.txt Visualize MCMC chain-mixing diagnostics using rank-based plots. mcmc_rank_hist() shows histograms of ranks per chain, mcmc_rank_overlay() plots overlaid rank step-lines, and mcmc_rank_ecdf() adds confidence bands or difference plots. ```r x <- example_mcmc_draws(chains = 4, params = 6) color_scheme_set("viridisE") # Rank histogram — one panel per (parameter × chain) mcmc_rank_hist(x, pars = c("alpha", "sigma"), ref_line = TRUE) # Overlaid rank step-lines — all chains on one panel per parameter mcmc_rank_overlay(x, regex_pars = "beta", ref_line = TRUE) # Rank ECDF with 99% simultaneous confidence bands mcmc_rank_ecdf(x, prob = 0.99) # ECDF difference plot: deviations from the ideal uniform distribution mcmc_rank_ecdf(x, prob = 0.99, plot_diff = TRUE) ``` -------------------------------- ### Highlight divergences in mcmc_scatter Source: https://github.com/stan-dev/bayesplot/blob/master/NEWS.md The `np` argument in `mcmc_scatter()` allows specifying NUTS parameters to highlight divergences in the plot. ```R mcmc_scatter(fit, pars = c("beta[1]", "beta[2]"), np = nuts_params(fit, "divergent__")) ``` -------------------------------- ### Arrange Multiple Bayespots in a Grid Source: https://context7.com/stan-dev/bayesplot/llms.txt Arrange multiple bayesplots (ggplot objects) in a shared grid, optionally aligning x/y axes and adding titles. This function wraps `gridExtra::arrangeGrob()`. ```r library(bayesplot) y <- example_y_data() yrep <- example_yrep_draws() stats <- c("sd", "median", "max", "min") color_scheme_set("pink") bayesplot_grid( plots = lapply(stats, function(s) ppc_stat(y, yrep, stat = s)), titles = stats, legends = FALSE, grid_args = list(ncol = 2) ) ``` ```r # Share x-axis limits across multiple interval plots x <- example_mcmc_draws(params = 6) color_scheme_set("teal") bayesplot_grid( mcmc_intervals(x, pars = c("alpha", "sigma")), mcmc_areas(x, regex_pars = "beta\[[1-3]\]"), xlim = c(-3, 3), grid_args = list(nrow = 1) ) ``` -------------------------------- ### Retrieve Underlying Tidy Data Frames Source: https://context7.com/stan-dev/bayesplot/llms.txt Companion `*_data()` functions return tidy data frames used by plot functions, enabling custom ggplot2 visualizations. These functions are useful for users who need fine-grained control over plot construction. ```r library(bayesplot) library(ggplot2) x <- example_mcmc_draws(chains = 4, params = 6) y <- example_y_data() yrep <- example_yrep_draws() # Retrieve trace data (includes value_rank for rank plots) trace_df <- mcmc_trace_data(x, pars = c("alpha", "sigma")) head(trace_df) # parameter value value_rank chain iteration ... ``` ```r # Retrieve interval summary data int_df <- mcmc_intervals_data(x, prob = 0.5, prob_outer = 0.9) # columns: parameter, ll, l, m, h, hh ``` ```r # Custom interval plot built from the data backend ggplot(int_df, aes(y = parameter)) + geom_segment(aes(x = ll, xend = hh, yend = parameter), color = "gray60") + geom_segment(aes(x = l, xend = h, yend = parameter), linewidth = 2) + geom_point(aes(x = m), size = 3, shape = 21, fill = "white") + theme_bw() + labs(title = "Custom interval plot from mcmc_intervals_data()") ``` ```r # Retrieve PPC data for custom plotting ppc_df <- ppc_data(y, yrep[1:10, ]) # columns: y_id, rep_id, rep_label, value, is_y, is_y_label ``` ```r # Retrieve test-statistic data stat_df <- ppc_stat_data(y, yrep, stat = "median") # columns: variable (y vs yrep), value of stat ``` -------------------------------- ### Plot Posterior Predictive Intervals for Observations Source: https://context7.com/stan-dev/bayesplot/llms.txt Use these functions to plot posterior predictive intervals for each observation, sorted or arranged along an x-axis variable, and overlaid with the observed values. This is useful for detecting systematic model misfits. Ensure `bayesplot` and `ggplot2` are loaded. ```r library(bayesplot) library(ggplot2) y <- example_y_data() yrep <- example_yrep_draws() x <- example_x_data() # covariate for x-axis ordering group <- example_group_data() # 50% inner and 90% outer predictive intervals vs observed y color_scheme_set("brightblue") ppc_intervals(y, yrep, x = x, prob = 0.5, prob_outer = 0.9) + labs(x = "x covariate", y = "y", title = "Posterior predictive intervals") # Ribbon version (polygon rather than line segments) color_scheme_set("teal") ppc_ribbon(y, yrep, x = x, prob = 0.5, prob_outer = 0.9) # Grouped intervals — one facet per group color_scheme_set("red") ppc_intervals_grouped(y, yrep, x = x, group = group, prob = 0.5) ``` -------------------------------- ### Add title to mcmc_pairs plot Source: https://github.com/stan-dev/bayesplot/blob/master/NEWS.md Use the `grid_args` argument in `mcmc_pairs()` to pass options to `gridExtra::arrangeGrob()`, such as adding a title to the plot. ```R mcmc_pairs(fit, pars = c("beta[1]", "beta[2]"), grid_args = list(title = "Posterior means and correlations")) ``` -------------------------------- ### Manage ggplot2 Theme for Bayespots Source: https://context7.com/stan-dev/bayesplot/llms.txt Control the ggplot2 theme applied to bayesplots. Changes affect only bayesplots and not other ggplot objects. Use `bayesplot_theme_set()` to apply a theme and `bayesplot_theme_update()` to modify specific elements. ```r library(bayesplot) library(ggplot2) x <- example_mcmc_draws() # Use the built-in default (serif, 12pt) bayesplot_theme_set() mcmc_hist(x) # Switch to a smaller sans-serif font bayesplot_theme_set(theme_default(base_size = 9, base_family = "sans")) mcmc_areas(x, regex_pars = "beta") # Use a completely different ggplot2 theme bayesplot_theme_set(theme_classic()) mcmc_trace(x, regex_pars = "beta") # Update individual elements (title size, panel background) bayesplot_theme_update( plot.title = element_text(size = 16, face = "bold"), panel.background = element_rect(fill = "gray98") ) # Restore the default bayesplot_theme_set() ``` -------------------------------- ### Data Backend Functions Source: https://context7.com/stan-dev/bayesplot/llms.txt Companion functions to major plot functions that return the underlying tidy data frame without creating a plot. Useful for custom visualizations with ggplot2. ```APIDOC ## Data Backend Functions ### `mcmc_trace_data()` / `mcmc_intervals_data()` / `mcmc_areas_data()` / `ppc_data()` / `ppc_stat_data()` **Description:** Every major plot function has a companion `*_data()` function that returns the underlying tidy data frame without creating a plot. These are intended for users who want to build custom visualizations with **ggplot2** on the same underlying data bayesplot would use. ### Usage: ```r # Retrieve trace data trace_df <- mcmc_trace_data(x, pars = c("alpha", "sigma")) head(trace_df) # Retrieve interval summary data int_df <- mcmc_intervals_data(x, prob = 0.5, prob_outer = 0.9) # Custom interval plot built from the data backend ggplot(int_df, aes(y = parameter)) + geom_segment(aes(x = ll, xend = hh, yend = parameter), color = "gray60") + geom_segment(aes(x = l, xend = h, yend = parameter), linewidth = 2) + geom_point(aes(x = m), size = 3, shape = 21, fill = "white") + theme_bw() + labs(title = "Custom interval plot from mcmc_intervals_data()") # Retrieve PPC data for custom plotting ppc_df <- ppc_data(y, yrep[1:10, ]) # Retrieve test-statistic data stat_df <- ppc_stat_data(y, yrep, stat = "median") ``` ``` -------------------------------- ### Control outer and inner probability intervals Source: https://github.com/stan-dev/bayesplot/blob/master/NEWS.md New `prob_outer` argument and existing `prob` argument in PPC interval plots control the display of outer and inner probability intervals, consistent with `mcmc_intervals()`. ```R ppc_intervals(y, y_rep, prob = 0.5, prob_outer = 0.9) ``` -------------------------------- ### Parallel coordinates plot for MCMC draws Source: https://github.com/stan-dev/bayesplot/blob/master/NEWS.md The new `mcmc_parcoord()` function creates parallel coordinates plots for MCMC draws, optionally including HMC/NUTS diagnostic information. ```R mcmc_parcoord(fit, pars = c("beta[1]", "beta[2]")) ``` -------------------------------- ### MCMC Autocorrelation Plot Source: https://context7.com/stan-dev/bayesplot/llms.txt Generates autocorrelation plots for MCMC draws using `mcmc_acf()`. Requires array input with chains and displays per-chain lag structure. ```R x <- example_mcmc_draws(chains = 4) color_scheme_set("green") mcmc_acf(x, pars = c("alpha", "beta[1]"), lags = 20) ``` -------------------------------- ### MCMC Autocorrelation Bar Plot Source: https://context7.com/stan-dev/bayesplot/llms.txt Creates bar plots of autocorrelation for MCMC draws using `mcmc_acf_bar()`. Useful for visualizing lag structure across chains. ```R mcmc_acf_bar(x, pars = c("alpha", "beta[1]"), lags = 15) ``` -------------------------------- ### Deprecated argument in mcmc_trace Source: https://github.com/stan-dev/bayesplot/blob/master/NEWS.md The `divergences` argument in `mcmc_trace()` is deprecated and replaced by `np` (NUTS parameters) to align with other functions. ```R mcmc_trace(fit, pars = "beta[1]", np = nuts_params(fit, "divergent__")) ``` -------------------------------- ### MCMC Density Areas Source: https://context7.com/stan-dev/bayesplot/llms.txt Shades credible intervals using `mcmc_areas()`. Can display density areas and outer tails, with options for different area calculation methods. ```R color_scheme_set("red") mcmc_areas( x, regex_pars = "beta\[[1-3]\]", prob = 0.8, area_method = "equal area" ) + labs(title = "Posterior distributions", subtitle = "with medians and 80% intervals") ``` -------------------------------- ### Plot Grid Source: https://context7.com/stan-dev/bayesplot/llms.txt Arrange multiple bayesplots (ggplot objects) in a shared grid, optionally aligning axes and adding titles. This function wraps `gridExtra::arrangeGrob()`. ```APIDOC ## Plot Grid ### `bayesplot_grid()` **Description:** Arrange multiple bayesplots (ggplot objects) in a shared grid, optionally aligning x/y axes and adding titles. Wraps `gridExtra::arrangeGrob()`. ### Usage: ```r # Arrange plots in a grid with specified titles and layout bayesplot_grid( plots = lapply(stats, function(s) ppc_stat(y, yrep, stat = s)), titles = stats, legends = FALSE, grid_args = list(ncol = 2) ) # Share x-axis limits across multiple interval plots in a single row bayesplot_grid( mcmc_intervals(x, pars = c("alpha", "sigma")), mcmc_areas(x, regex_pars = "beta\[[1-3]\]"), xlim = c(-3, 3), grid_args = list(nrow = 1) ) ``` ``` -------------------------------- ### Histogram breaks argument Source: https://github.com/stan-dev/bayesplot/blob/master/NEWS.md The `breaks` argument in histogram plots can now be used as an alternative to `binwidth` for controlling binning. ```R mcmc_hist(log_lik, binwidth = 0.1, breaks = seq(-5, 5, by = 0.5)) ``` -------------------------------- ### Control bayesplot ggplot2 theme Source: https://github.com/stan-dev/bayesplot/blob/master/NEWS.md Use these functions to manage the ggplot theme specifically for bayesplot plots. They mirror ggplot2's theme functions but only affect bayesplot output. ```R bayesplot_theme_set() bayesplot_theme_get() bayesplot_theme_update() bayesplot_theme_replace() ``` -------------------------------- ### MCMC Ridgeline Areas Source: https://context7.com/stan-dev/bayesplot/llms.txt Generates ridgeline plots of density areas using `mcmc_areas_ridges()`. Suitable for compact display of hierarchically related parameters. ```R color_scheme_set("purple") mcmc_areas_ridges(x, regex_pars = "beta", border_size = 0.75) + ggtitle("Hierarchical beta parameters") ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.