- 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 points and intervals
- Intervals with multiple probability levels
- Intervals with densities
- Posterior fits
- Quantile dotplots
- Posterior predictions
- 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 `rstanarm`

. 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(forcats)
library(tidyr)
library(purrr)
library(modelr)
library(tidybayes)
library(ggplot2)
library(ggstance)
library(ggridges)
library(rstan)
library(rstanarm)
library(cowplot)
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 = stan_lmer(response ~ (1|condition), data = ABC,
prior = normal(0, 1, autoscale = FALSE),
prior_aux = student_t(3, 0, 1, autoscale = FALSE),
adapt_delta = .99)
```

The results look like this:

```
## stan_lmer
## family: gaussian [identity]
## formula: response ~ (1 | condition)
## observations: 50
## ------
## Median MAD_SD
## (Intercept) 0.6 0.4
##
## Auxiliary parameter(s):
## Median MAD_SD
## sigma 0.6 0.1
##
## Error terms:
## Groups Name Std.Dev.
## condition (Intercept) 1.16
## Residual 0.57
## Num. levels: condition 5
##
## Sample avg. posterior predictive distribution of y:
## Median MAD_SD
## mean_PPD 0.6 0.1
##
## ------
## * For help interpreting the printed output see ?print.stanreg
## * For info on the priors used see ?prior_summary.stanreg
```

`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 variables names so that we know what variables we can extract from the model:

```
## [1] "(Intercept)" "b[(Intercept) condition:A]"
## [3] "b[(Intercept) condition:B]" "b[(Intercept) condition:C]"
## [5] "b[(Intercept) condition:D]" "b[(Intercept) condition:E]"
## [7] "sigma" "Sigma[condition:(Intercept),(Intercept)]"
## [9] "accept_stat__" "stepsize__"
## [11] "treedepth__" "n_leapfrog__"
## [13] "divergent__" "energy__"
```

Here, `(Intercept)`

is the global mean, and the `b`

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

`b[(Intercept) condition:A]`

`b[(Intercept) condition:B]`

`b[(Intercept) condition:C]`

`b[(Intercept) condition:D]`

`b[(Intercept) condition:E]`

We might want a data frame where each row is a draw from either `b[(Intercept) condition:A]`

, `b[(Intercept) condition:B]`

, `...: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.

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 model variables and their indices into tidy-format data frames.

Given a parameter like this:

`b[(Intercept) condition:D]`

We can provide `spread_draws`

with a column specification like this:

`b[term,group]`

Where `term`

corresponds to `(Intercept)`

and `group`

to `condition:D`

. There is nothing too magical about what `spread_draws`

does with this specification: under the hood, it splits the parameter 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 `b[(Intercept) condition:D]`

has indices `(Intercept)`

and `condition:D`

, and `spread_draws`

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

:

.chain | .iteration | .draw | term | group | b |
---|---|---|---|---|---|

1 | 1 | 1 | (Intercept) | condition:A | -0.3783698 |

1 | 1 | 1 | (Intercept) | condition:B | 0.3564460 |

1 | 1 | 1 | (Intercept) | condition:C | 1.4980078 |

1 | 1 | 1 | (Intercept) | condition:D | 0.8478156 |

1 | 1 | 1 | (Intercept) | condition:E | -1.0165481 |

1 | 2 | 2 | (Intercept) | condition:A | -0.2675461 |

1 | 2 | 2 | (Intercept) | condition:B | 0.5141313 |

1 | 2 | 2 | (Intercept) | condition:C | 1.7507237 |

1 | 2 | 2 | (Intercept) | condition:D | 0.9151790 |

1 | 2 | 2 | (Intercept) | condition:E | -0.8985269 |

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

.chain | .iteration | .draw | t | g | b |
---|---|---|---|---|---|

1 | 1 | 1 | (Intercept) | condition:A | -0.3783698 |

1 | 1 | 1 | (Intercept) | condition:B | 0.3564460 |

1 | 1 | 1 | (Intercept) | condition:C | 1.4980078 |

1 | 1 | 1 | (Intercept) | condition:D | 0.8478156 |

1 | 1 | 1 | (Intercept) | condition:E | -1.0165481 |

1 | 2 | 2 | (Intercept) | condition:A | -0.2675461 |

1 | 2 | 2 | (Intercept) | condition:B | 0.5141313 |

1 | 2 | 2 | (Intercept) | condition:C | 1.7507237 |

1 | 2 | 2 | (Intercept) | condition:D | 0.9151790 |

1 | 2 | 2 | (Intercept) | condition:E | -0.8985269 |

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 `group`

and the value of `b`

for the corresponding condition:

.chain | .iteration | .draw | group | b |
---|---|---|---|---|

1 | 1 | 1 | condition:A | -0.3783698 |

1 | 1 | 1 | condition:B | 0.3564460 |

1 | 1 | 1 | condition:C | 1.4980078 |

1 | 1 | 1 | condition:D | 0.8478156 |

1 | 1 | 1 | condition:E | -1.0165481 |

1 | 2 | 2 | condition:A | -0.2675461 |

1 | 2 | 2 | condition:B | 0.5141313 |

1 | 2 | 2 | condition:C | 1.7507237 |

1 | 2 | 2 | condition:D | 0.9151790 |

1 | 2 | 2 | condition:E | -0.8985269 |

Since all the groups in this case are from the `condition`

factor, we may also want to separate out a column just containing the corresponding condition (`A`

, `B`

, `C`

, etc). We can do that using `tidyr::separate`

:

.chain | .iteration | .draw | group | condition | b |
---|---|---|---|---|---|

1 | 1 | 1 | condition | A | -0.3783698 |

1 | 1 | 1 | condition | B | 0.3564460 |

1 | 1 | 1 | condition | C | 1.4980078 |

1 | 1 | 1 | condition | D | 0.8478156 |

1 | 1 | 1 | condition | E | -1.0165481 |

1 | 2 | 2 | condition | A | -0.2675461 |

1 | 2 | 2 | condition | B | 0.5141313 |

1 | 2 | 2 | condition | C | 1.7507237 |

1 | 2 | 2 | condition | D | 0.9151790 |

1 | 2 | 2 | condition | E | -0.8985269 |

Alternatively, we could change the `sep`

argument to `spread_draws`

to also split on `:`

(`sep`

is a regular expression). **Note:** This works in this example, but will not work well on rstanarm models where interactions between factors are used as grouping levels in a multilevel model, thus `:`

is not included in the default separators.

.chain | .iteration | .draw | group | condition | b |
---|---|---|---|---|---|

1 | 1 | 1 | condition | A | -0.3783698 |

1 | 1 | 1 | condition | B | 0.3564460 |

1 | 1 | 1 | condition | C | 1.4980078 |

1 | 1 | 1 | condition | D | 0.8478156 |

1 | 1 | 1 | condition | E | -1.0165481 |

1 | 2 | 2 | condition | A | -0.2675461 |

1 | 2 | 2 | condition | B | 0.5141313 |

1 | 2 | 2 | condition | C | 1.7507237 |

1 | 2 | 2 | condition | D | 0.9151790 |

1 | 2 | 2 | condition | E | -0.8985269 |

**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 or interval functions can also be applied using the `point_interval`

function.

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

.chain | .iteration | .draw | (Intercept) | sigma |
---|---|---|---|---|

1 | 1 | 1 | 0.2770340 | 0.5299852 |

1 | 2 | 2 | 0.2796086 | 0.5308416 |

1 | 3 | 3 | 0.2693029 | 0.5326245 |

1 | 4 | 4 | 0.1055822 | 0.5260694 |

1 | 5 | 5 | 0.3701722 | 0.5454265 |

1 | 6 | 6 | 0.5640671 | 0.5428926 |

1 | 7 | 7 | 0.5264201 | 0.5609093 |

1 | 8 | 8 | 0.5578231 | 0.5507146 |

1 | 9 | 9 | 0.9927603 | 0.5224025 |

1 | 10 | 10 | 0.4832814 | 0.6090149 |

Like with `b[term,group]`

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

:

(Intercept) | (Intercept).lower | (Intercept).upper | sigma | sigma.lower | sigma.upper | .width | .point | .interval |
---|---|---|---|---|---|---|---|---|

0.6150627 | -0.3716496 | 1.572178 | 0.5615301 | 0.4621166 | 0.6984192 | 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, `(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:

(Intercept) | (Intercept).lower | (Intercept).upper | sigma | sigma.lower | sigma.upper | .width | .point | .interval |
---|---|---|---|---|---|---|---|---|

0.6150627 | -0.3716496 | 1.572178 | 0.5615301 | 0.4621166 | 0.6984192 | 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 |
---|---|---|---|---|---|---|

(Intercept) | 0.6150627 | -0.3716496 | 1.5721775 | 0.95 | median | qi |

sigma | 0.5615301 | 0.4621166 | 0.6984192 | 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 `b`

, we can apply `median_qi`

(or other functions in the `point_interval`

family) as we did before:

group | b | .lower | .upper | .width | .point | .interval |
---|---|---|---|---|---|---|

condition:A | -0.4268644 | -1.3975186 | 0.6197463 | 0.95 | median | qi |

condition:B | 0.3693680 | -0.6375897 | 1.4112357 | 0.95 | median | qi |

condition:C | 1.2066038 | 0.2267204 | 2.2669145 | 0.95 | median | qi |

condition:D | 0.3794252 | -0.5864682 | 1.4430031 | 0.95 | median | qi |

condition:E | -1.5011988 | -2.5043110 | -0.5047681 | 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 `group`

. `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, `b`

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

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

group | b | .lower | .upper | .width | .point | .interval |
---|---|---|---|---|---|---|

condition:A | -0.4268644 | -1.3975186 | 0.6197463 | 0.95 | median | qi |

condition:B | 0.3693680 | -0.6375897 | 1.4112357 | 0.95 | median | qi |

condition:C | 1.2066038 | 0.2267204 | 2.2669145 | 0.95 | median | qi |

condition:D | 0.3794252 | -0.5864682 | 1.4430031 | 0.95 | median | qi |

condition:E | -1.5011988 | -2.5043110 | -0.5047681 | 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 (`(Intercept)`

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

).

We can gather draws from `(Intercept)`

and `b`

together in a single data frame:

.chain | .iteration | .draw | (Intercept) | group | b |
---|---|---|---|---|---|

1 | 1 | 1 | 0.2770340 | condition:A | -0.3783698 |

1 | 1 | 1 | 0.2770340 | condition:B | 0.3564460 |

1 | 1 | 1 | 0.2770340 | condition:C | 1.4980078 |

1 | 1 | 1 | 0.2770340 | condition:D | 0.8478156 |

1 | 1 | 1 | 0.2770340 | condition:E | -1.0165481 |

1 | 2 | 2 | 0.2796086 | condition:A | -0.2675461 |

1 | 2 | 2 | 0.2796086 | condition:B | 0.5141313 |

1 | 2 | 2 | 0.2796086 | condition:C | 1.7507237 |

1 | 2 | 2 | 0.2796086 | condition:D | 0.9151790 |

1 | 2 | 2 | 0.2796086 | condition:E | -0.8985269 |

Within each draw, `(Intercept)`

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

. 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(`(Intercept)`, b[,group]) %>%
mutate(condition_mean = `(Intercept)` + b) %>%
median_qi(condition_mean)
```

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

condition:A | 0.1958506 | -0.1371752 | 0.5432926 | 0.95 | median | qi |

condition:B | 1.0017273 | 0.6565704 | 1.3295293 | 0.95 | median | qi |

condition:C | 1.8352753 | 1.4811222 | 2.1833405 | 0.95 | median | qi |

condition:D | 1.0133598 | 0.6708869 | 1.3561820 | 0.95 | median | qi |

condition:E | -0.8792313 | -1.2345900 | -0.5350516 | 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`

:

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

condition:A | 0.1958506 | -0.1371752 | 0.5432926 | 0.95 | median | qi |

condition:B | 1.0017273 | 0.6565704 | 1.3295293 | 0.95 | median | qi |

condition:C | 1.8352753 | 1.4811222 | 2.1833405 | 0.95 | median | qi |

condition:D | 1.0133598 | 0.6708869 | 1.3561820 | 0.95 | median | qi |

condition:E | -0.8792313 | -1.2345900 | -0.5350516 | 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(`(Intercept)`, b[,group]) %>%
median_qi(condition_mean = `(Intercept)` + b, .width = c(.95, .8, .5))
```

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

condition:A | 0.1958506 | -0.1371752 | 0.5432926 | 0.95 | median | qi |

condition:B | 1.0017273 | 0.6565704 | 1.3295293 | 0.95 | median | qi |

condition:C | 1.8352753 | 1.4811222 | 2.1833405 | 0.95 | median | qi |

condition:D | 1.0133598 | 0.6708869 | 1.3561820 | 0.95 | median | qi |

condition:E | -0.8792313 | -1.2345900 | -0.5350516 | 0.95 | median | qi |

condition:A | 0.1958506 | -0.0220723 | 0.4174080 | 0.80 | median | qi |

condition:B | 1.0017273 | 0.7795036 | 1.2178557 | 0.80 | median | qi |

condition:C | 1.8352753 | 1.6115417 | 2.0610689 | 0.80 | median | qi |

condition:D | 1.0133598 | 0.7930202 | 1.2292221 | 0.80 | median | qi |

condition:E | -0.8792313 | -1.1073296 | -0.6625777 | 0.80 | median | qi |

condition:A | 0.1958506 | 0.0814303 | 0.3113113 | 0.50 | median | qi |

condition:B | 1.0017273 | 0.8873369 | 1.1150516 | 0.50 | median | qi |

condition:C | 1.8352753 | 1.7177633 | 1.9536512 | 0.50 | median | qi |

condition:D | 1.0133598 | 0.8986673 | 1.1219872 | 0.50 | median | qi |

condition:E | -0.8792313 | -1.0047803 | -0.7572831 | 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 points 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 `rstanarm::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.1013359 |

A | 1 | NA | NA | 2 | 0.0120625 |

A | 1 | NA | NA | 3 | 0.1221181 |

A | 1 | NA | NA | 4 | 0.0662090 |

A | 1 | NA | NA | 5 | 0.3282843 |

A | 1 | NA | NA | 6 | 0.3769907 |

A | 1 | NA | NA | 7 | 0.0179667 |

A | 1 | NA | NA | 8 | 0.0416166 |

A | 1 | NA | NA | 9 | 0.3686505 |

A | 1 | NA | NA | 10 | 0.2571611 |

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

instead of `geom_pointintervalh`

, which summarizes draws into point summaries 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 `rstanarm::posterior_linpred`

, `add_predicted_draws`

is analogous to `rstanarm::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.102`

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() +
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()
```

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

dataset:

We can plot 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 can get difficult to judge by group, so could be 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")
```

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(b[,,condition], sep = "[, :]") %>%
compare_levels(b, by = condition) %>%
ggplot(aes(y = condition, x = b)) +
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(b[,,condition], sep = "[, :]") %>%
compare_levels(b, by = condition) %>%
ungroup() %>%
mutate(condition = reorder(condition, b)) %>%
ggplot(aes(y = condition, x = b)) +
geom_halfeyeh() +
geom_vline(xintercept = 0, linetype = "dashed")
```

Here’s an ordinal model with a categorical predictor:

```
data(esoph)
m_esoph_rs = stan_polr(tobgp ~ agegp, data = esoph, prior = R2(0.25), prior_counts = dirichlet(1))
```

The `rstanarm::posterior_linpred`

function for ordinal regression models in rstanarm returns only the link-level prediction for each draw (in contrast to `brms::fitted.brmsfit`

, which returns one prediction per category for ordinal models, see the ordinal regression examples in `vignette("tidy-brms")`

). The philosophy of `tidybayes`

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

models, `add_fitted_draws`

just returns the link-level prediction (**Note**: setting `scale = "response"`

for such models will not usually make sense).

For example, here is a plot of the link-level fit:

```
esoph %>%
data_grid(agegp) %>%
add_fitted_draws(m_esoph_rs, scale = "linear") %>%
ggplot(aes(x = as.numeric(agegp), y = .value)) +
stat_lineribbon(color = "red") +
scale_fill_brewer(palette = "Greys")
```

This can be hard to interpret. To turn this into predicted probabilities on a per-category basis, we have to use the fact that an ordinal logistic regression defines the probability of an outcome in category \(j\) **or less** as:

\[ \textrm{logit}\left[Pr(Y\le j)\right] = \alpha_j - \beta x \]

Thus, the probability of category \(j\) is:

\[ \begin{align} Pr(Y = j) &= Pr(Y \le j) - Pr(Y \le j - 1)\\ &= \textrm{logit}^{-1}(\alpha_j - \beta x) - \textrm{logit}^{-1}(\alpha_{j-1} - \beta x) \end{align} \]

To derive these values, we need two things:

The \(\alpha_j\) values. These are threshold parameters fitted by the model. For convenience, if there are \(k\) levels, we will take \(\alpha_k = +\infty\), since the probability of being in the top level or below it is 1.

The \(\beta x\) values. These are just the

`.value`

column returned by`add_fitted_draws`

.

The thresholds in `rstanarm`

are coefficients with names containing `|`

, indicating which categories they are thresholds between. We can see those parameters in the list of variables in the model:

```
## [1] "agegp.L" "agegp.Q" "agegp.C" "agegp^4" "agegp^5" "0-9g/day|10-19"
## [7] "10-19|20-29" "20-29|30+" "accept_stat__" "stepsize__" "treedepth__" "n_leapfrog__"
## [13] "divergent__" "energy__"
```

We can extract those automatically by using the `regex = TRUE`

argument to `gather_draws`

to find all variables containing a `|`

character. We will then use `summarise_all(list)`

to turn these thresholds into a list column, and add a final threshold equal to \(+\infty\) (to represent the highest category):

```
thresholds = m_esoph_rs %>%
gather_draws(`.*[|].*`, regex = TRUE) %>%
group_by(.draw) %>%
select(.draw, threshold = .value) %>%
summarise_all(list) %>%
mutate(threshold = map(threshold, ~ c(., Inf)))
head(thresholds, 10)
```

.draw | threshold |
---|---|

1 | c(-0.797154093082517, 0.320858016562741, 1.61550962456089, Inf) |

2 | c(-0.860240124498572, 0.148526178612682, 1.28440595658395, Inf) |

3 | c(-1.10816167255982, 0.287093541412914, 1.30105769410709, Inf) |

4 | c(-0.722140711543583, 0.248491079567628, 1.25824044278972, Inf) |

5 | c(-1.08452355270964, 0.221741424864375, 1.15994130037193, Inf) |

6 | c(-1.13777028774901, 0.249353798786929, 1.26701324242416, Inf) |

7 | c(-1.00864202596385, 0.097697465374094, 1.25462687541106, Inf) |

8 | c(-0.918169587301167, 0.0545351111008215, 0.957580002543823, Inf) |

9 | c(-0.931801528480973, 0.337318473804281, 1.44035836683091, Inf) |

10 | c(-0.951923909707334, 0.0972527776058318, 1.07797749658227, Inf) |

For example, the threshold vector from one row of this data frame (i.e., from one draw from the posterior) looks like this:

```
## [[1]]
## [1] -0.7971541 0.3208580 1.6155096 Inf
```

We can combine those thresholds (the \(\alpha_j\) values from the above formula) with the `.value`

from `add_fitted_draws`

(\(\beta x\) from the above formula) to calculate per-category probabilities:

```
esoph %>%
data_grid(agegp) %>%
add_fitted_draws(m_esoph_rs, scale = "linear") %>%
inner_join(thresholds, by = ".draw") %>%
mutate(`P(Y = category)` = map2(threshold, .value, function(alpha, beta_x)
# this part is logit^-1(alpha_j - beta*x) - logit^-1(alpha_j-1 - beta*x)
plogis(alpha - beta_x) -
plogis(lag(alpha, default = -Inf) - beta_x)
)) %>%
mutate(.category = list(levels(esoph$tobgp))) %>%
unnest() %>%
ggplot(aes(x = agegp, y = `P(Y = category)`, color = .category)) +
stat_pointinterval(position = position_dodge(width = .4)) +
scale_size_continuous(guide = FALSE) +
scale_color_manual(values = brewer.pal(6, "Blues")[-c(1,2)])
```

It is hard to see the changes in categories in the above plot; let’s try something that gives a better gist of the distribution within each year:

```
esoph %>%
data_grid(agegp) %>%
add_fitted_draws(m_esoph_rs, scale = "linear") %>%
inner_join(thresholds, by = ".draw") %>%
mutate(`P(Y = category)` = map2(threshold, .value, function(alpha, beta_x)
# this part is logit^-1(alpha_j - beta*x) - logit^-1(alpha_j-1 - beta*x)
plogis(alpha - beta_x) -
plogis(lag(alpha, default = -Inf) - beta_x)
)) %>%
mutate(.category = list(levels(esoph$tobgp))) %>%
unnest() %>%
ggplot(aes(x = `P(Y = category)`, y = .category)) +
stat_summaryh(fun.x = median, geom = "barh", fill = "gray75", width = 1, color = "white") +
stat_pointintervalh() +
coord_cartesian(expand = FALSE) +
facet_grid(. ~ agegp, switch = "x") +
theme_classic() +
theme(strip.background = element_blank(), strip.placement = "outside") +
ggtitle("P(tobacco consumption category | age group)") +
xlab("age group")
```

This output should be very similar to the output from the corresponding `m_esoph_brm`

model in `vignette("tidy-brms")`

(modulo different priors), though it takes a bit more work to produce in `rstanarm`

compared to `brms`

.