- Introduction
- Setup
- Example dataset
- Model
- Extracting draws from a fit in tidy-format using
`spread_draws`

- Point summaries and intervals
- Combining variables with different indices in a single tidy format data frame
- Plotting point summaries and intervals
- Intervals with multiple probability levels
- Intervals with densities
- Posterior fits
- Quantile dotplots
- Posterior predictions
- Posterior predictions, Kruschke-style
- Fit/prediction curves
- Comparing levels of a factor
- Ordinal models

This vignette describes how to use the `tidybayes`

package to extract tidy data frames of draws from posterior distributions of model variables, fits, and predictions from `brms::brm`

. For a more general introduction to `tidybayes`

and its use on general-purpose Bayesian modeling languages (like Stan and JAGS), see `vignette(“tidybayes”)`

.

The following libraries are required to run this vignette:

```
library(magrittr)
library(dplyr)
library(purrr)
library(forcats)
library(tidyr)
library(modelr)
library(tidybayes)
library(ggplot2)
library(ggstance)
library(ggridges)
library(cowplot)
library(rstan)
library(brms)
library(ggrepel)
library(RColorBrewer)
library(gganimate)
theme_set(theme_tidybayes() + panel_border() + background_grid())
```

These options help Stan run faster:

To demonstrate `tidybayes`

, we will use a simple dataset with 10 observations from 5 conditions each:

```
set.seed(5)
n = 10
n_condition = 5
ABC =
tibble(
condition = rep(c("A","B","C","D","E"), n),
response = rnorm(n * 5, c(0,1,2,1,-1), 0.5)
)
```

A snapshot of the data looks like this:

condition | response |
---|---|

A | -0.4204277 |

B | 1.6921797 |

C | 1.3722541 |

D | 1.0350714 |

E | -0.1442796 |

A | -0.3014540 |

B | 0.7639168 |

C | 1.6823143 |

D | 0.8571132 |

E | -0.9309459 |

This is a typical tidy format data frame: one observation per row. Graphically:

Let’s fit a hierarchical model with shrinkage towards a global mean:

```
m = brm(response ~ (1|condition), data = ABC, control = list(adapt_delta = .99),
prior = c(
prior(normal(0, 1), class = Intercept),
prior(student_t(3, 0, 1), class = sd),
prior(student_t(3, 0, 1), class = sigma)
))
```

`## Compiling the C++ model`

`## Start sampling`

The results look like this:

```
## Family: gaussian
## Links: mu = identity; sigma = identity
## Formula: response ~ (1 | condition)
## Data: ABC (Number of observations: 50)
## Samples: 4 chains, each with iter = 2000; warmup = 1000; thin = 1;
## total post-warmup samples = 4000
##
## Group-Level Effects:
## ~condition (Number of levels: 5)
## Estimate Est.Error l-95% CI u-95% CI Eff.Sample Rhat
## sd(Intercept) 1.15 0.42 0.60 2.26 1027 1.00
##
## Population-Level Effects:
## Estimate Est.Error l-95% CI u-95% CI Eff.Sample Rhat
## Intercept 0.48 0.47 -0.51 1.37 1019 1.00
##
## Family Specific Parameters:
## Estimate Est.Error l-95% CI u-95% CI Eff.Sample Rhat
## sigma 0.56 0.06 0.46 0.70 2191 1.00
##
## Samples were drawn using sampling(NUTS). For each parameter, Eff.Sample
## is a crude measure of effective sample size, and Rhat is the potential
## scale reduction factor on split chains (at convergence, Rhat = 1).
```

`spread_draws`

Now that we have our results, the fun begins: getting the draws out in a tidy format! First, we’ll use the `get_variables`

function to get a list of raw model variable names so that we know what variables we can extract from the model:

```
## [1] "b_Intercept" "sd_condition__Intercept" "sigma" "r_condition[A,Intercept]"
## [5] "r_condition[B,Intercept]" "r_condition[C,Intercept]" "r_condition[D,Intercept]" "r_condition[E,Intercept]"
## [9] "lp__" "accept_stat__" "stepsize__" "treedepth__"
## [13] "n_leapfrog__" "divergent__" "energy__"
```

Here, `b_Intercept`

is the global mean, and the `r_condition[]`

variables are offsets from that mean for each condition. Given these variables:

`r_condition[A,Intercept]`

`r_condition[B,Intercept]`

`r_condition[C,Intercept]`

`r_condition[D,Intercept]`

`r_condition[E,Intercept]`

We might want a data frame where each row is a draw from either `r_condition[A,Intercept]`

, `r_condition[B,Intercept]`

, `...[C,...]`

, `...[D,...]`

, or `...[E,...]`

, and where we have columns indexing which chain/iteration/draw the row came from and which condition (`A`

to `E`

) it is for. That would allow us to easily compute quantities grouped by condition, or generate plots by condition using ggplot, or even merge draws with the original data to plot data and posteriors simultaneously.

The workhorse of `tidybayes`

is the `spread_draws`

function, which does this extraction for us. It includes a simple specification format that we can use to extract variables and their indices into tidy-format data frames.

Given a variable in the model like this:

`r_condition[D,Intercept]`

We can provide `spread_draws`

with a column specification like this:

`r_condition[condition,term]`

Where `condition`

corresponds to `D`

and `term`

corresponds to `Intercept`

. There is nothing too magical about what `spread_draws`

does with this specification: under the hood, it splits the variable indices by commas and spaces (you can split by other characters by changing the `sep`

argument). It lets you assign columns to the resulting indices in order. So `r_condition[D,Intercept]`

has indices `D`

and `Intercept`

, and `spread_draws`

lets us extract these indices as columns in the resulting tidy data frame of draws from `r_condition`

:

.chain | .iteration | .draw | condition | term | r_condition |
---|---|---|---|---|---|

1 | 1 | 1 | A | Intercept | -0.5810329 |

1 | 1 | 1 | B | Intercept | 0.3633415 |

1 | 1 | 1 | C | Intercept | 1.4677376 |

1 | 1 | 1 | D | Intercept | 0.0577004 |

1 | 1 | 1 | E | Intercept | -1.5453720 |

1 | 2 | 2 | A | Intercept | -0.1060177 |

1 | 2 | 2 | B | Intercept | 0.6355170 |

1 | 2 | 2 | C | Intercept | 1.2752448 |

1 | 2 | 2 | D | Intercept | 0.9783754 |

1 | 2 | 2 | E | Intercept | -1.5197823 |

We can choose whatever names we want for the index columns; e.g.:

.chain | .iteration | .draw | c | t | r_condition |
---|---|---|---|---|---|

1 | 1 | 1 | A | Intercept | -0.5810329 |

1 | 1 | 1 | B | Intercept | 0.3633415 |

1 | 1 | 1 | C | Intercept | 1.4677376 |

1 | 1 | 1 | D | Intercept | 0.0577004 |

1 | 1 | 1 | E | Intercept | -1.5453720 |

1 | 2 | 2 | A | Intercept | -0.1060177 |

1 | 2 | 2 | B | Intercept | 0.6355170 |

1 | 2 | 2 | C | Intercept | 1.2752448 |

1 | 2 | 2 | D | Intercept | 0.9783754 |

1 | 2 | 2 | E | Intercept | -1.5197823 |

But the more descriptive and less cryptic names from the previous example are probably preferable.

In this particular model, there is only one term (`Intercept`

), thus we could omit that index altogether to just get each `condition`

and the value of `r_condition`

for that condition:

.chain | .iteration | .draw | condition | r_condition |
---|---|---|---|---|

1 | 1 | 1 | A | -0.5810329 |

1 | 1 | 1 | B | 0.3633415 |

1 | 1 | 1 | C | 1.4677376 |

1 | 1 | 1 | D | 0.0577004 |

1 | 1 | 1 | E | -1.5453720 |

1 | 2 | 2 | A | -0.1060177 |

1 | 2 | 2 | B | 0.6355170 |

1 | 2 | 2 | C | 1.2752448 |

1 | 2 | 2 | D | 0.9783754 |

1 | 2 | 2 | E | -1.5197823 |

**Note:** If you have used `spread_draws`

with a raw sample from Stan or JAGS, you may be used to using `recover_types`

before `spread_draws`

to get index column values back (e.g. if the index was a factor). This is not necessary when using `spread_draws`

on `rstanarm`

models, because those models already contain that information in their variable names. For more on `recover_types`

, see `vignette(“tidybayes”)`

.

`tidybayes`

provides a family of functions for generating point summaries and intervals from draws in a tidy format. These functions follow the naming scheme `[median|mean|mode]_[qi|hdi]`

, for example, `median_qi`

, `mean_qi`

, `mode_hdi`

, and so on. The first name (before the `_`

) indicates the type of point summary, and the second name indicates the type of interval. `qi`

yields a quantile interval (a.k.a. equi-tailed interval, central interval, or percentile interval) and `hdi`

yields a highest (posterior) density interval. Custom point summary or interval functions can also be applied using the `point_interval`

function.

For example, we might extract the draws corresponding to posterior distributions of the overall mean and standard deviation of observations:

.chain | .iteration | .draw | b_Intercept | sigma |
---|---|---|---|---|

1 | 1 | 1 | 0.6995477 | 0.4881950 |

1 | 2 | 2 | 0.2155526 | 0.4961438 |

1 | 3 | 3 | 0.4425632 | 0.5423818 |

1 | 4 | 4 | 0.5093357 | 0.5398252 |

1 | 5 | 5 | 0.1774891 | 0.6119993 |

1 | 6 | 6 | 0.4622683 | 0.4818569 |

1 | 7 | 7 | -0.3361366 | 0.6241829 |

1 | 8 | 8 | -0.0545059 | 0.5503045 |

1 | 9 | 9 | 0.1123446 | 0.5831841 |

1 | 10 | 10 | -0.4945380 | 0.5932715 |

Like with `r_condition[condition,term]`

, this gives us a tidy data frame. If we want the median and 95% quantile interval of the variables, we can apply `median_qi`

:

b_Intercept | b_Intercept.lower | b_Intercept.upper | sigma | sigma.lower | sigma.upper | .width | .point | .interval |
---|---|---|---|---|---|---|---|---|

0.493102 | -0.5148802 | 1.369306 | 0.5564453 | 0.4574353 | 0.699386 | 0.95 | median | qi |

We can specify the columns we want to get medians and intervals from, as above, or if we omit the list of columns, `median_qi`

will use every column that is not a grouping column or a special column (like `.chain`

, `.iteration`

, or `.draw`

). Thus in the above example, `b_Intercept`

and `sigma`

are redundant arguments to `median_qi`

because they are also the only columns we gathered from the model. So we can simplify this to:

b_Intercept | b_Intercept.lower | b_Intercept.upper | sigma | sigma.lower | sigma.upper | .width | .point | .interval |
---|---|---|---|---|---|---|---|---|

0.493102 | -0.5148802 | 1.369306 | 0.5564453 | 0.4574353 | 0.699386 | 0.95 | median | qi |

If you would rather have a long-format list of intervals, use `gather_draws`

instead:

.variable | .value | .lower | .upper | .width | .point | .interval |
---|---|---|---|---|---|---|

b_Intercept | 0.4931020 | -0.5148802 | 1.369306 | 0.95 | median | qi |

sigma | 0.5564453 | 0.4574353 | 0.699386 | 0.95 | median | qi |

For more on `gather_draws`

, see `vignette(“tidybayes”)`

.

When we have a model variable with one or more indices, such as `r_condition`

, we can apply `median_qi`

(or other functions in the `point_interval`

family) as we did before:

condition | r_condition | .lower | .upper | .width | .point | .interval |
---|---|---|---|---|---|---|

A | -0.3033179 | -1.2269679 | 0.7615788 | 0.95 | median | qi |

B | 0.4985908 | -0.4153369 | 1.5975198 | 0.95 | median | qi |

C | 1.3272511 | 0.4191741 | 2.4098032 | 0.95 | median | qi |

D | 0.5110338 | -0.4163398 | 1.5554848 | 0.95 | median | qi |

E | -1.3772997 | -2.3018246 | -0.3225438 | 0.95 | median | qi |

How did `median_qi`

know what to aggregate? Data frames returned by `spread_draws`

are automatically grouped by all index variables you pass to it; in this case, that means `spread_draws`

groups its results by `condition`

. `median_qi`

respects those groups, and calculates the point summaries and intervals within all groups. Then, because no columns were passed to `median_qi`

, it acts on the only non-special (`.`

-prefixed) and non-group column, `r_condition`

. So the above shortened syntax is equivalent to this more verbose call:

```
m %>%
spread_draws(r_condition[condition,]) %>%
group_by(condition) %>% # this line not necessary (done by spread_draws)
median_qi(r_condition) # b is not necessary (it is the only non-group column)
```

condition | r_condition | .lower | .upper | .width | .point | .interval |
---|---|---|---|---|---|---|

A | -0.3033179 | -1.2269679 | 0.7615788 | 0.95 | median | qi |

B | 0.4985908 | -0.4153369 | 1.5975198 | 0.95 | median | qi |

C | 1.3272511 | 0.4191741 | 2.4098032 | 0.95 | median | qi |

D | 0.5110338 | -0.4163398 | 1.5554848 | 0.95 | median | qi |

E | -1.3772997 | -2.3018246 | -0.3225438 | 0.95 | median | qi |

`spread_draws`

and `gather_draws`

support extracting variables that have different indices into the same data frame. Indices with the same name are automatically matched up, and values are duplicated as necessary to produce one row per all combination of levels of all indices. For example, we might want to calculate the mean within each condition (call this `condition_mean`

). In this model, that mean is the intercept (`b_Intercept`

) plus the effect for a given condition (`r_condition`

).

We can gather draws from `b_Intercept`

and `r_condition`

together in a single data frame:

.chain | .iteration | .draw | b_Intercept | condition | r_condition |
---|---|---|---|---|---|

1 | 1 | 1 | 0.6995477 | A | -0.5810329 |

1 | 1 | 1 | 0.6995477 | B | 0.3633415 |

1 | 1 | 1 | 0.6995477 | C | 1.4677376 |

1 | 1 | 1 | 0.6995477 | D | 0.0577004 |

1 | 1 | 1 | 0.6995477 | E | -1.5453720 |

1 | 2 | 2 | 0.2155526 | A | -0.1060177 |

1 | 2 | 2 | 0.2155526 | B | 0.6355170 |

1 | 2 | 2 | 0.2155526 | C | 1.2752448 |

1 | 2 | 2 | 0.2155526 | D | 0.9783754 |

1 | 2 | 2 | 0.2155526 | E | -1.5197823 |

Within each draw, `b_Intercept`

is repeated as necessary to correspond to every index of `r_condition`

. Thus, the `mutate`

function from dplyr can be used to find their sum, `condition_mean`

(which is the mean for each condition):

```
m %>%
spread_draws(`b_Intercept`, r_condition[condition,]) %>%
mutate(condition_mean = b_Intercept + r_condition) %>%
median_qi(condition_mean)
```

condition | condition_mean | .lower | .upper | .width | .point | .interval |
---|---|---|---|---|---|---|

A | 0.1891991 | -0.1526974 | 0.5419131 | 0.95 | median | qi |

B | 0.9974171 | 0.6521849 | 1.3419413 | 0.95 | median | qi |

C | 1.8336155 | 1.4763845 | 2.1817297 | 0.95 | median | qi |

D | 1.0108162 | 0.6492899 | 1.3614141 | 0.95 | median | qi |

E | -0.8904363 | -1.2409219 | -0.5204142 | 0.95 | median | qi |

`median_qi`

uses tidy evaluation (see `vignette("tidy-evaluation", package = "rlang")`

), so it can take column expressions, not just column names. Thus, we can simplify the above example by moving the calculation of `condition_mean`

from `mutate`

into `median_qi`

:

```
m %>%
spread_draws(b_Intercept, r_condition[condition,]) %>%
median_qi(condition_mean = b_Intercept + r_condition)
```

condition | condition_mean | .lower | .upper | .width | .point | .interval |
---|---|---|---|---|---|---|

A | 0.1891991 | -0.1526974 | 0.5419131 | 0.95 | median | qi |

B | 0.9974171 | 0.6521849 | 1.3419413 | 0.95 | median | qi |

C | 1.8336155 | 1.4763845 | 2.1817297 | 0.95 | median | qi |

D | 1.0108162 | 0.6492899 | 1.3614141 | 0.95 | median | qi |

E | -0.8904363 | -1.2409219 | -0.5204142 | 0.95 | median | qi |

Plotting point summaries and with one interval is straightforward using the `ggplot2::geom_pointrange`

or `ggstance::geom_pointrangeh`

geoms:

`median_qi`

and its sister functions can also produce an arbitrary number of probability intervals by setting the `.width =`

argument:

```
m %>%
spread_draws(b_Intercept, r_condition[condition,]) %>%
median_qi(condition_mean = b_Intercept + r_condition, .width = c(.95, .8, .5))
```

condition | condition_mean | .lower | .upper | .width | .point | .interval |
---|---|---|---|---|---|---|

A | 0.1891991 | -0.1526974 | 0.5419131 | 0.95 | median | qi |

B | 0.9974171 | 0.6521849 | 1.3419413 | 0.95 | median | qi |

C | 1.8336155 | 1.4763845 | 2.1817297 | 0.95 | median | qi |

D | 1.0108162 | 0.6492899 | 1.3614141 | 0.95 | median | qi |

E | -0.8904363 | -1.2409219 | -0.5204142 | 0.95 | median | qi |

A | 0.1891991 | -0.0326947 | 0.4104882 | 0.80 | median | qi |

B | 0.9974171 | 0.7784890 | 1.2146419 | 0.80 | median | qi |

C | 1.8336155 | 1.6060139 | 2.0551949 | 0.80 | median | qi |

D | 1.0108162 | 0.7864282 | 1.2319521 | 0.80 | median | qi |

E | -0.8904363 | -1.1195142 | -0.6552443 | 0.80 | median | qi |

A | 0.1891991 | 0.0695642 | 0.3056698 | 0.50 | median | qi |

B | 0.9974171 | 0.8860555 | 1.1113185 | 0.50 | median | qi |

C | 1.8336155 | 1.7167302 | 1.9471993 | 0.50 | median | qi |

D | 1.0108162 | 0.8932430 | 1.1280797 | 0.50 | median | qi |

E | -0.8904363 | -1.0128192 | -0.7636899 | 0.50 | median | qi |

The results are in a tidy format: one row per group and uncertainty interval width (`.width`

). This facilitates plotting. For example, assigning `-.width`

to the `size`

aesthetic will show all intervals, making thicker lines correspond to smaller intervals. The `geom_pointintervalh`

geom, provided by tidybayes, is a shorthand for a `geom_pointrangeh`

with `xmin`

, `xmax`

, and `size`

set appropriately based on the `.lower`

, `.upper`

, and `.width`

columns in the data to produce plots of point summaries with multiple probability levels:

To see the density along with the intervals, we can use `geom_eyeh`

(horizontal “eye plots”, which combine intervals with violin plots), or `geom_halfeyeh`

(horizontal interval + density plots):

Rather than calculating conditional means manually as in the previous example, we could use `add_fitted_draws`

, which is analogous to `brms::fitted.brmsfit`

or `brms::posterior_linpred`

(giving posterior draws from the model’s linear predictor, in this case, posterior distributions of conditional means), but uses a tidy data format. We can combine it with `modelr::data_grid`

to first generate a grid describing the fits we want, then transform that grid into a long-format data frame of draws from posterior fits:

condition | .row | .chain | .iteration | .draw | .value |
---|---|---|---|---|---|

A | 1 | NA | NA | 1 | 0.1185148 |

A | 1 | NA | NA | 2 | 0.1095349 |

A | 1 | NA | NA | 3 | 0.3208845 |

A | 1 | NA | NA | 4 | 0.1882641 |

A | 1 | NA | NA | 5 | 0.1641242 |

A | 1 | NA | NA | 6 | 0.0746312 |

A | 1 | NA | NA | 7 | -0.0213145 |

A | 1 | NA | NA | 8 | -0.0594389 |

A | 1 | NA | NA | 9 | 0.3771889 |

A | 1 | NA | NA | 10 | 0.1104230 |

To plot this example, we’ll also show the use of `stat_pointintervalh`

instead of `geom_pointintervalh`

, which summarizes draws into points and intervals within ggplot:

Intervals are nice if the alpha level happens to line up with whatever decision you are trying to make, but getting a shape of the posterior is better (hence eye plots, above). On the other hand, making inferences from density plots is imprecise (estimating the area of one shape as a proportion of another is a hard perceptual task). Reasoning about probability in frequency formats is easier, motivating quantile dotplots, which also allow precise estimation of arbitrary intervals (down to the dot resolution of the plot, here 100):

```
ABC %>%
data_grid(condition) %>%
add_fitted_draws(m) %>%
do(tibble(.value = quantile(.$.value, ppoints(100)))) %>%
ggplot(aes(x = .value)) +
geom_dotplot(binwidth = .04) +
facet_grid(fct_rev(condition) ~ .) +
scale_y_continuous(breaks = NULL)
```

The idea is to get away from thinking about the posterior as indicating one canonical point or interval, but instead to represent it as (say) 100 approximately equally likely points.

Where `add_fitted_draws`

is analogous to `brms::fitted.brmsfit`

(or `brms::posterior_linpred`

), `add_predicted_draws`

is analogous to `brms::predict.brmsfit`

(`brms::posterior_predict`

), giving draws from the posterior predictive distribution.

Here is an example of posterior predictive distributions plotted using `ggridges::geom_density_ridges`

:

```
ABC %>%
data_grid(condition) %>%
add_predicted_draws(m) %>%
ggplot(aes(x = .prediction, y = condition)) +
geom_density_ridges()
```

`## Picking joint bandwidth of 0.0993`

We could also use `tidybayes::stat_intervalh`

to plot predictive bands alongside the data:

```
ABC %>%
data_grid(condition) %>%
add_predicted_draws(m) %>%
ggplot(aes(y = condition, x = .prediction)) +
stat_intervalh(.width = c(.50, .80, .95, .99)) +
geom_point(aes(x = response), data = ABC) +
scale_color_brewer()
```

Altogether, data, posterior predictions, and posterior distributions of the means:

```
grid = ABC %>%
data_grid(condition)
fits = grid %>%
add_fitted_draws(m)
preds = grid %>%
add_predicted_draws(m)
ABC %>%
ggplot(aes(y = condition, x = response)) +
stat_intervalh(aes(x = .prediction), data = preds) +
stat_pointintervalh(aes(x = .value), data = fits, .width = c(.66, .95), position = position_nudge(y = -0.2)) +
geom_point() +
scale_color_brewer()
```

The above approach to posterior predictions integrates over the parameter uncertainty to give a single posterior predictive distribution. Another approach, often used by John Kruschke in his book Doing Bayesian Data Analysis, is to attempt to show both the predictive uncertainty and the parameter uncertainty simultaneously by showing several possible predictive distributions implied by the posterior.

We can do this pretty easily by asking for the distributional parameters for a given prediction implied by the posterior. We’ll do it explicitly here by setting `dpar = c("mu", "sigma")`

in `add_fitted_draws`

. Rather than specifying the parameters explicitly, you can also just set `dpar = TRUE`

to get draws from all distributional parameters in a model, and this will work for any response distribution supported by brms.

For a more detailed description of how these charts (and some useful variations on them), see Solomon Kurz’s excellent blog post on the topic.

```
ABC %>%
data_grid(condition) %>%
add_fitted_draws(m, dpar = c("mu", "sigma"), n = 100) %>%
mutate(
lower = qnorm(.001, mu, sigma),
upper = qnorm(.999, mu, sigma),
response = map2(lower, upper, seq, length.out = 101),
density = pmap(list(response, mu, sigma), dnorm)
) %>%
unnest() %>%
ggplot(aes(x = response, y = condition)) +
geom_ridgeline(aes(height = density, group = interaction(condition, .draw)),
fill = NA, color = adjustcolor("black", alpha.f = 1/20)
) +
geom_point(data = ABC, shape = 21, fill = brewer.pal(3, "Blues")[[2]], size = 2)
```

To demonstrate drawing fit curves with uncertainty, let’s fit a slightly naive model to part of the `mtcars`

dataset:

We can draw fit curves with probability bands:

```
mtcars %>%
group_by(cyl) %>%
data_grid(hp = seq_range(hp, n = 51)) %>%
add_fitted_draws(m_mpg) %>%
ggplot(aes(x = hp, y = mpg, color = ordered(cyl))) +
stat_lineribbon(aes(y = .value)) +
geom_point(data = mtcars) +
scale_fill_brewer(palette = "Greys") +
scale_color_brewer(palette = "Set2")
```

Or we can sample a reasonable number of fit lines (say 100) and overplot them:

```
mtcars %>%
group_by(cyl) %>%
data_grid(hp = seq_range(hp, n = 101)) %>%
add_fitted_draws(m_mpg, n = 100) %>%
ggplot(aes(x = hp, y = mpg, color = ordered(cyl))) +
geom_line(aes(y = .value, group = paste(cyl, .draw)), alpha = .1) +
geom_point(data = mtcars) +
scale_color_brewer(palette = "Dark2")
```

Or we can create animated hypothetical outcome plots (HOPs) of fit lines:

```
set.seed(123456)
ndraws = 50
p = mtcars %>%
group_by(cyl) %>%
data_grid(hp = seq_range(hp, n = 101)) %>%
add_fitted_draws(m_mpg, n = ndraws) %>%
ggplot(aes(x = hp, y = mpg, color = ordered(cyl))) +
geom_line(aes(y = .value, group = paste(cyl, .draw))) +
geom_point(data = mtcars) +
scale_color_brewer(palette = "Dark2") +
transition_states(.draw, 0, 1) +
shadow_mark(future = TRUE, color = "gray50", alpha = 1/20)
animate(p, nframes = ndraws, fps = 2.5, width = 576, height = 384, res = 96, type = "cairo")
```

Or, for posterior predictions (instead of fits), we can go back to probability bands:

```
mtcars %>%
group_by(cyl) %>%
data_grid(hp = seq_range(hp, n = 101)) %>%
add_predicted_draws(m_mpg) %>%
ggplot(aes(x = hp, y = mpg, color = ordered(cyl), fill = ordered(cyl))) +
stat_lineribbon(aes(y = .prediction), .width = c(.95, .80, .50), alpha = 1/4) +
geom_point(data = mtcars) +
scale_fill_brewer(palette = "Set2") +
scale_color_brewer(palette = "Dark2")
```

This gets difficult to judge by group, so probably better to facet into multiple plots. Fortunately, since we are using ggplot, that functionality is built in:

```
mtcars %>%
group_by(cyl) %>%
data_grid(hp = seq_range(hp, n = 101)) %>%
add_predicted_draws(m_mpg) %>%
ggplot(aes(x = hp, y = mpg)) +
stat_lineribbon(aes(y = .prediction), .width = c(.99, .95, .8, .5), color = brewer.pal(5, "Blues")[[5]]) +
geom_point(data = mtcars) +
scale_fill_brewer() +
facet_grid(. ~ cyl, space = "free_x", scales = "free_x")
```

`brm`

also allows us to set up submodels for parameters of the response distribution *other than* the location (e.g., mean). For example, we can allow a variance parameter, such as the standard deviation, to also be some function of the predictors.

This approach can be helpful in cases of non-constant variance (also called *heteroskedasticity* by folks who like obfuscation via Latin). E.g., imagine two groups, each with different mean response *and variance*:

```
set.seed(1234)
AB = tibble(
group = rep(c("a", "b"), each = 20),
response = rnorm(40, mean = rep(c(1, 5), each = 20), sd = rep(c(1, 3), each = 20))
)
AB %>%
ggplot(aes(x = response, y = group)) +
geom_point()
```

Here is a model that lets the mean *and standard deviation* of `response`

be dependent on `group`

:

`## Compiling the C++ model`

`## Start sampling`

We can plot the posterior distribution of the mean `response`

alongside posterior predictive intervals and the data:

```
grid = AB %>%
data_grid(group)
fits = grid %>%
add_fitted_draws(m_ab)
preds = grid %>%
add_predicted_draws(m_ab)
AB %>%
ggplot(aes(x = response, y = group)) +
geom_halfeyeh(aes(x = .value), relative_scale = 0.7, position = position_nudge(y = 0.1), data = fits) +
stat_intervalh(aes(x = .prediction), data = preds) +
geom_point(data = AB) +
scale_color_brewer()
```

This shows posteriors of the mean of each group (black intervals and the density plots) and posterior predictive intervals (blue).

The predictive intervals in group `b`

are larger than in group `a`

because the model fits a different standard deviation for each group. We can see how the corresponding distributional parameter, `sigma`

, changes by extracting it using the `dpar`

argument to `add_fitted_draws`

:

```
grid %>%
add_fitted_draws(m_ab, dpar = TRUE) %>%
ggplot(aes(x = sigma, y = group)) +
geom_halfeyeh() +
geom_vline(xintercept = 0, linetype = "dashed")
```

By setting `dpar = TRUE`

, all distributional parameters are added as additional columns in the result of `add_fitted_draws`

; if you only want a specific parameter, you can specify it (or a list of just the parameters you want). In the above model, `dpar = TRUE`

is equivalent to `dpar = list("mu", "sigma")`

.

If we wish compare the means from each condition, `compare_levels`

facilitates comparisons of the value of some variable across levels of a factor. By default it computes all pairwise differences.

Let’s demonstrate `compare_levels`

with another plotting geom, `geom_halfeyeh`

, which gives horizontal “half-eye” plots, combining intervals with a density plot:

```
#N.B. the syntax for compare_levels is experimental and may change
m %>%
spread_draws(r_condition[condition,]) %>%
compare_levels(r_condition, by = condition) %>%
ggplot(aes(y = condition, x = r_condition)) +
geom_halfeyeh()
```

If you prefer “caterpillar” plots, ordered by something like the mean of the difference, you can reorder the factor before plotting:

```
#N.B. the syntax for compare_levels is experimental and may change
m %>%
spread_draws(r_condition[condition,]) %>%
compare_levels(r_condition, by = condition) %>%
ungroup() %>%
mutate(condition = reorder(condition, r_condition)) %>%
ggplot(aes(y = condition, x = r_condition)) +
geom_halfeyeh() +
geom_vline(xintercept = 0, linetype = "dashed")
```

The `brms::fitted.brmsfit`

function for ordinal and multinomial regression models in brms returns multiple variables for each draw: one for each outcome category (in contrast to `rstanarm::stan_polr`

models, which return draws from the latent linear predictor). The philosophy of `tidybayes`

is to tidy whatever format is output by a model, so in keeping with that philosophy, when applied to ordinal and multinomial `brms`

models, `add_fitted_draws`

adds an additional column called `.category`

and a separate row containing the variable for each category is output for every draw and predictor.

We’ll fit a model using the `mtcars`

dataset that predicts the number of cylinders in a car given the car’s mileage (in miles per gallon). While this is a little backwards causality-wise (presumably the number of cylinders causes the mileage, if anything), that does not mean this is not a fine prediction task (I could probably tell someone who knows something about cars the MPG of a car and they could do reasonably well at guessing the number of cylinders in the engine).

Before we fit the model, let’s clean the dataset by making the `cyl`

column an ordered factor (by default it is just a number):

mpg | cyl | disp | hp | drat | wt | qsec | vs | am | gear | carb |
---|---|---|---|---|---|---|---|---|---|---|

21.0 | 6 | 160 | 110 | 3.90 | 2.620 | 16.46 | 0 | 1 | 4 | 4 |

21.0 | 6 | 160 | 110 | 3.90 | 2.875 | 17.02 | 0 | 1 | 4 | 4 |

22.8 | 4 | 108 | 93 | 3.85 | 2.320 | 18.61 | 1 | 1 | 4 | 1 |

21.4 | 6 | 258 | 110 | 3.08 | 3.215 | 19.44 | 1 | 0 | 3 | 1 |

18.7 | 8 | 360 | 175 | 3.15 | 3.440 | 17.02 | 0 | 0 | 3 | 2 |

18.1 | 6 | 225 | 105 | 2.76 | 3.460 | 20.22 | 1 | 0 | 3 | 1 |

Then we’ll fit an ordinal regression model:

`## Compiling the C++ model`

`## Start sampling`

`add_fitted_draws`

will include a `.category`

column, and `.value`

will contain draws from the posterior distribution for the probability that the response is in that category. For example, here is the fit for the first row in the dataset:

mpg | .row | .category | .value | .lower | .upper | .width | .point | .interval |
---|---|---|---|---|---|---|---|---|

21 | 1 | 4 | 0.2802613 | 0.0457070 | 0.6904619 | 0.95 | median | qi |

21 | 1 | 6 | 0.7049680 | 0.2913318 | 0.9522769 | 0.95 | median | qi |

21 | 1 | 8 | 0.0035370 | 0.0000064 | 0.0765461 | 0.95 | median | qi |

We could plot fit lines for fitted probabilities against the dataset:

```
data_plot = mtcars_clean %>%
ggplot(aes(x = mpg, y = cyl, color = cyl)) +
geom_point() +
scale_color_brewer(palette = "Dark2", name = "cyl")
fit_plot = mtcars_clean %>%
data_grid(mpg = seq_range(mpg, n = 101)) %>%
# we can use the `value` argument to give the column with values of
# transformed linear predictors a more precise name and the
# `category` argument to give the column with category labels
# a more precise name
add_fitted_draws(m_cyl, value = "P(cyl | mpg)", category = "cyl") %>%
ggplot(aes(x = mpg, y = `P(cyl | mpg)`, color = cyl)) +
stat_lineribbon(aes(fill = cyl), alpha = 1/5) +
scale_color_brewer(palette = "Dark2") +
scale_fill_brewer(palette = "Dark2")
plot_grid(ncol = 1, align = "v",
data_plot,
fit_plot
)
```

As [Michael Betancourt points out], the above display does not let you see the correlation between `P(cyl|mpg)`

for different values of `cyl`

at a particular value of `mpg`

. For example, in the portion of the posterior where `P(cyl = 6|mpg = 20)`

is high, `P(cyl = 4|mpg = 20)`

and `P(cyl = 8|mpg = 20)`

must be low (since these must add up to 1).

One way to see this correlation might be to employ hypothetical outcome plots (HOPs) just for the fit line, “detach”ing it from the ribbon (another alternative would be to use HOPs on top of line ensembles, as demonstrated earlier in this document). By employing animation, you can see how the lines move in tandem or opposition to each other, revealing some patterns in how they are correlated:

```
ndraws = 50
p = mtcars_clean %>%
data_grid(mpg = seq_range(mpg, n = 101)) %>%
add_fitted_draws(m_cyl, value = "P(cyl | mpg)", category = "cyl") %>%
ggplot(aes(x = mpg, y = `P(cyl | mpg)`, color = cyl)) +
# we remove the `.draw` column from the data for stat_lineribbon so that the same ribbons
# are drawn on every frame (since we use .draw to determine the transitions below)
stat_lineribbon(aes(fill = cyl), alpha = 1/5, color = NA, data = . %>% select(-.draw)) +
# we use sample_draws to subsample at the level of geom_line (rather than for the full dataset
# as in previous HOPs examples) because we need the full set of draws for stat_lineribbon above
geom_line(aes(group = paste(.draw, cyl)), size = 1, data = . %>% sample_draws(ndraws)) +
scale_color_brewer(palette = "Dark2") +
scale_fill_brewer(palette = "Dark2") +
transition_manual(.draw)
animate(p, nframes = ndraws, fps = 2.5, width = 576, height = 192, res = 96, type = "cairo")
```