Labeller option for mcmc_pairs in bayesplot

Hi, I’m trying to use a labeller for mcmc_pairs to label the subplots along the diagonal. I’ve seen the discussion here which provides a workaround, but I’m working with an older script where it seems like I was able to pass a labeller argument to grid_args like so:

devtools::install_github("stan-dev/bayesplot")
library("bayesplot")
library("ggplot2")

x <- example_mcmc_draws() 

labeller <- as_labeller(x=c('alpha' = "Alpha", 'sigma' = "Sigma", 'beta[1]' = "Beta-one", 'beta[2]' = "Beta-two"  ))

pairs_plot <- mcmc_pairs(x, diag_fun = "dens", grid_args = list(labeller = labeller))

However, now this doesn’t work. If something like this doesn’t exist, would it be difficult to implement?

I’m using R 4.1, cmdstanr 0.4.0, and bayesplot 1.10.0 on a Mac.

I’m not sure if bayesplot provides a way to relabel the subplots within a typical workflow, but here’s a workaround for now: The parameter names are coming from the Parameter dimension of x (the mcmc_draws object). You can change these names and it will be reflected in the plots. Here’s an updated version of your example:

library(bayesplot)
library(tidyverse)

x <- example_mcmc_draws() 

dimnames(x)
#> $Iteration
#> NULL
#> 
#> $Chain
#> [1] "chain:1" "chain:2" "chain:3" "chain:4"
#> 
#> $Parameter
#> [1] "alpha"   "sigma"   "beta[1]" "beta[2]"

dimnames(x)$Parameter = c("Alpha", "Sigma", "Beta-one", "Beta-two")

dimnames(x)
#> $Iteration
#> NULL
#> 
#> $Chain
#> [1] "chain:1" "chain:2" "chain:3" "chain:4"
#> 
#> $Parameter
#> [1] "Alpha"    "Sigma"    "Beta-one" "Beta-two"

p <- mcmc_pairs(x, diag_fun = "dens")

p

Created on 2023-04-04 with reprex v2.0.2

That’s a nice workaround, as long as there aren’t too many parameters. Thanks!

If you have large numbers of parameters, you can often use various string functions to make systematic changes to the names, rather than hardcoding each one by hand. Here’s an example of the basic idea:

library(tidyverse)
library(english)

# Vector of parameter names
params = c("alpha", "sigma", paste0("beta[", 1:12, "]"))
params
#>  [1] "alpha"    "sigma"    "beta[1]"  "beta[2]"  "beta[3]"  "beta[4]" 
#>  [7] "beta[5]"  "beta[6]"  "beta[7]"  "beta[8]"  "beta[9]"  "beta[10]"
#> [13] "beta[11]" "beta[12]"

# Replacement vector for number names
nums = str_extract(params, "[0-9]+")
nums = as.character(english(as.numeric(nums)))
nums
#>  [1] ""       ""       "one"    "two"    "three"  "four"   "five"   "six"   
#>  [9] "seven"  "eight"  "nine"   "ten"    "eleven" "twelve"

# Update params to new names
params.new = str_to_title(params) %>% 
  str_replace(., "\\[[0-9]+\\]", paste0("-", nums))
params.new
#>  [1] "Alpha"       "Sigma"       "Beta-one"    "Beta-two"    "Beta-three" 
#>  [6] "Beta-four"   "Beta-five"   "Beta-six"    "Beta-seven"  "Beta-eight" 
#> [11] "Beta-nine"   "Beta-ten"    "Beta-eleven" "Beta-twelve"

Created on 2023-04-05 with reprex v2.0.2

1 Like