Introduction

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”).

Example dataset

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

A snapshot of the data looks like this:

## # A tibble: 10 x 2
##    condition response
##    <chr>        <dbl>
##  1 A           -0.420
##  2 B            1.69 
##  3 C            1.37 
##  4 D            1.04 
##  5 E           -0.144
##  6 A           -0.301
##  7 B            0.764
##  8 C            1.68 
##  9 D            0.857
## 10 E           -0.931

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

Model

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

## 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.17      0.43     0.61     2.22       1016 1.00
## 
## Population-Level Effects: 
##           Estimate Est.Error l-95% CI u-95% CI Eff.Sample Rhat
## Intercept     0.48      0.46    -0.47     1.37        963 1.01
## 
## Family Specific Parameters: 
##       Estimate Est.Error l-95% CI u-95% CI Eff.Sample Rhat
## sigma     0.56      0.06     0.46     0.69       2099 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).

Extracting draws from a fit in tidy-format using 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.

Gathering variable indices into a separate column in a tidy format data frame

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:

m %>%
  spread_draws(r_condition[condition,term]) %>%
  head(10)
## # A tibble: 10 x 6
## # Groups:   condition, term [5]
##    .chain .iteration .draw condition term      r_condition
##     <int>      <int> <int> <chr>     <chr>           <dbl>
##  1      1          1     1 A         Intercept       0.300
##  2      1          1     1 B         Intercept       1.23 
##  3      1          1     1 C         Intercept       1.92 
##  4      1          1     1 D         Intercept       0.947
##  5      1          1     1 E         Intercept      -0.707
##  6      1          2     2 A         Intercept       0.453
##  7      1          2     2 B         Intercept       1.03 
##  8      1          2     2 C         Intercept       1.93 
##  9      1          2     2 D         Intercept       1.10 
## 10      1          2     2 E         Intercept      -1.14

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

m %>%
  spread_draws(r_condition[c,t]) %>%
  head(10)
## # A tibble: 10 x 6
## # Groups:   c, t [5]
##    .chain .iteration .draw c     t         r_condition
##     <int>      <int> <int> <chr> <chr>           <dbl>
##  1      1          1     1 A     Intercept       0.300
##  2      1          1     1 B     Intercept       1.23 
##  3      1          1     1 C     Intercept       1.92 
##  4      1          1     1 D     Intercept       0.947
##  5      1          1     1 E     Intercept      -0.707
##  6      1          2     2 A     Intercept       0.453
##  7      1          2     2 B     Intercept       1.03 
##  8      1          2     2 C     Intercept       1.93 
##  9      1          2     2 D     Intercept       1.10 
## 10      1          2     2 E     Intercept      -1.14

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:

m %>%
  spread_draws(r_condition[condition,]) %>%
  head(10)
## # A tibble: 10 x 5
## # Groups:   condition [5]
##    .chain .iteration .draw condition r_condition
##     <int>      <int> <int> <chr>           <dbl>
##  1      1          1     1 A               0.300
##  2      1          1     1 B               1.23 
##  3      1          1     1 C               1.92 
##  4      1          1     1 D               0.947
##  5      1          1     1 E              -0.707
##  6      1          2     2 A               0.453
##  7      1          2     2 B               1.03 
##  8      1          2     2 C               1.93 
##  9      1          2     2 D               1.10 
## 10      1          2     2 E              -1.14

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”).

Point summaries and intervals

With simple model variables

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:

m %>%
  spread_draws(b_Intercept, sigma) %>%
  head(10)
## # A tibble: 10 x 5
##    .chain .iteration .draw b_Intercept sigma
##     <int>      <int> <int>       <dbl> <dbl>
##  1      1          1     1     -0.147  0.554
##  2      1          2     2      0.0901 0.573
##  3      1          3     3      0.113  0.649
##  4      1          4     4      1.16   0.514
##  5      1          5     5      1.08   0.593
##  6      1          6     6      1.19   0.599
##  7      1          7     7      1.03   0.649
##  8      1          8     8      1.06   0.547
##  9      1          9     9      1.17   0.563
## 10      1         10    10      0.309  0.562

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:

m %>%
  spread_draws(b_Intercept, sigma) %>%
  median_qi(b_Intercept, sigma)
## # A tibble: 1 x 9
##   b_Intercept b_Intercept.lower b_Intercept.upper sigma sigma.lower sigma.upper .width .point .interval
##         <dbl>             <dbl>             <dbl> <dbl>       <dbl>       <dbl>  <dbl> <chr>  <chr>    
## 1       0.520            -0.467              1.37 0.556       0.459       0.693   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:

m %>%
  spread_draws(b_Intercept, sigma) %>%
  median_qi()
## # A tibble: 1 x 9
##   b_Intercept b_Intercept.lower b_Intercept.upper sigma sigma.lower sigma.upper .width .point .interval
##         <dbl>             <dbl>             <dbl> <dbl>       <dbl>       <dbl>  <dbl> <chr>  <chr>    
## 1       0.520            -0.467              1.37 0.556       0.459       0.693   0.95 median qi

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

m %>%
  gather_draws(b_Intercept, sigma) %>%
  median_qi()
## # A tibble: 2 x 7
##   .variable   .value .lower .upper .width .point .interval
##   <chr>        <dbl>  <dbl>  <dbl>  <dbl> <chr>  <chr>    
## 1 b_Intercept  0.520 -0.467  1.37    0.95 median qi       
## 2 sigma        0.556  0.459  0.693   0.95 median qi

For more on gather_draws, see vignette(“tidybayes”).

With indexed model variables

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:

m %>%
  spread_draws(r_condition[condition,]) %>%
  median_qi()
## # A tibble: 5 x 7
##   condition r_condition .lower .upper .width .point .interval
##   <chr>           <dbl>  <dbl>  <dbl>  <dbl> <chr>  <chr>    
## 1 A              -0.305 -1.20   0.720   0.95 median qi       
## 2 B               0.494 -0.401  1.52    0.95 median qi       
## 3 C               1.33   0.432  2.36    0.95 median qi       
## 4 D               0.516 -0.405  1.54    0.95 median qi       
## 5 E              -1.38  -2.29  -0.389   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)
## # A tibble: 5 x 7
##   condition r_condition .lower .upper .width .point .interval
##   <chr>           <dbl>  <dbl>  <dbl>  <dbl> <chr>  <chr>    
## 1 A              -0.305 -1.20   0.720   0.95 median qi       
## 2 B               0.494 -0.401  1.52    0.95 median qi       
## 3 C               1.33   0.432  2.36    0.95 median qi       
## 4 D               0.516 -0.405  1.54    0.95 median qi       
## 5 E              -1.38  -2.29  -0.389   0.95 median qi

Combining variables with different indices in a single tidy format data frame

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:

m %>% 
  spread_draws(b_Intercept, r_condition[condition,]) %>%
  head(10)
## # A tibble: 10 x 6
## # Groups:   condition [5]
##    .chain .iteration .draw b_Intercept condition r_condition
##     <int>      <int> <int>       <dbl> <chr>           <dbl>
##  1      1          1     1     -0.147  A               0.300
##  2      1          1     1     -0.147  B               1.23 
##  3      1          1     1     -0.147  C               1.92 
##  4      1          1     1     -0.147  D               0.947
##  5      1          1     1     -0.147  E              -0.707
##  6      1          2     2      0.0901 A               0.453
##  7      1          2     2      0.0901 B               1.03 
##  8      1          2     2      0.0901 C               1.93 
##  9      1          2     2      0.0901 D               1.10 
## 10      1          2     2      0.0901 E              -1.14

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)
## # A tibble: 5 x 7
##   condition condition_mean .lower .upper .width .point .interval
##   <chr>              <dbl>  <dbl>  <dbl>  <dbl> <chr>  <chr>    
## 1 A                  0.194 -0.142  0.539   0.95 median qi       
## 2 B                  0.999  0.651  1.34    0.95 median qi       
## 3 C                  1.83   1.49   2.18    0.95 median qi       
## 4 D                  1.02   0.680  1.34    0.95 median qi       
## 5 E                 -0.890 -1.24  -0.531   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)
## # A tibble: 5 x 7
##   condition condition_mean .lower .upper .width .point .interval
##   <chr>              <dbl>  <dbl>  <dbl>  <dbl> <chr>  <chr>    
## 1 A                  0.194 -0.142  0.539   0.95 median qi       
## 2 B                  0.999  0.651  1.34    0.95 median qi       
## 3 C                  1.83   1.49   2.18    0.95 median qi       
## 4 D                  1.02   0.680  1.34    0.95 median qi       
## 5 E                 -0.890 -1.24  -0.531   0.95 median qi

Plotting point summaries and intervals

Plotting point summaries and with one interval is straightforward using the ggplot2::geom_pointrange or ggstance::geom_pointrangeh geoms:

m %>%
  spread_draws(b_Intercept, r_condition[condition,]) %>%
  median_qi(condition_mean = b_Intercept + r_condition) %>%
  ggplot(aes(y = condition, x = condition_mean, xmin = .lower, xmax = .upper)) +
  geom_pointrangeh()

Intervals with multiple probability levels

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))
## # A tibble: 15 x 7
##    condition condition_mean  .lower .upper .width .point .interval
##    <chr>              <dbl>   <dbl>  <dbl>  <dbl> <chr>  <chr>    
##  1 A                  0.194 -0.142   0.539   0.95 median qi       
##  2 B                  0.999  0.651   1.34    0.95 median qi       
##  3 C                  1.83   1.49    2.18    0.95 median qi       
##  4 D                  1.02   0.680   1.34    0.95 median qi       
##  5 E                 -0.890 -1.24   -0.531   0.95 median qi       
##  6 A                  0.194 -0.0240  0.425   0.8  median qi       
##  7 B                  0.999  0.780   1.23    0.8  median qi       
##  8 C                  1.83   1.60    2.05    0.8  median qi       
##  9 D                  1.02   0.796   1.24    0.8  median qi       
## 10 E                 -0.890 -1.12   -0.660   0.8  median qi       
## 11 A                  0.194  0.0787  0.312   0.5  median qi       
## 12 B                  0.999  0.885   1.12    0.5  median qi       
## 13 C                  1.83   1.72    1.95    0.5  median qi       
## 14 D                  1.02   0.901   1.13    0.5  median qi       
## 15 E                 -0.890 -1.01   -0.771   0.5  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:

m %>%
  spread_draws(b_Intercept, r_condition[condition,]) %>%
  median_qi(condition_mean = b_Intercept + r_condition, .width = c(.95, .66)) %>%
  ggplot(aes(y = condition, x = condition_mean)) +
  geom_pointintervalh() 

Intervals with densities

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):

Posterior fits

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:

## # A tibble: 10 x 6
## # Groups:   condition, .row [1]
##    condition  .row .chain .iteration .draw   .value
##    <chr>     <int>  <int>      <int> <int>    <dbl>
##  1 A             1     NA         NA     1  0.153  
##  2 A             1     NA         NA     2  0.543  
##  3 A             1     NA         NA     3  0.00485
##  4 A             1     NA         NA     4 -0.0288 
##  5 A             1     NA         NA     5  0.417  
##  6 A             1     NA         NA     6  0.566  
##  7 A             1     NA         NA     7  0.110  
##  8 A             1     NA         NA     8  0.333  
##  9 A             1     NA         NA     9 -0.142  
## 10 A             1     NA         NA    10  0.0918

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:

Quantile dotplots

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):

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.

Posterior predictions

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:

## Picking joint bandwidth of 0.1

We could also use tidybayes::stat_intervalh to plot predictive bands alongside the data:

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

Fit/prediction curves

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:

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

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

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:

Extracting of distributional regression parameters

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:

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:

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:

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").

Comparing levels of a factor

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:

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

Ordinal models

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.

Ordinal model with continuous 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
## 1 21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
## 2 21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
## 3 22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
## 4 21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
## 5 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2
## 6 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:

## # A tibble: 3 x 9
## # Groups:   mpg, .row [1]
##     mpg  .row .category  .value     .lower .upper .width .point .interval
##   <dbl> <int> <fct>       <dbl>      <dbl>  <dbl>  <dbl> <chr>  <chr>    
## 1    21     1 4         0.280   0.0457     0.690    0.95 median qi       
## 2    21     1 6         0.705   0.291      0.952    0.95 median qi       
## 3    21     1 8         0.00354 0.00000635 0.0765   0.95 median qi

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

While talking about the mean for an ordinal distribution often does not make sense, in this particular case one could argue that the expected number of cylinders for a car given its miles per gallon is a meaningful quantity. We could plot the posterior distribution for the average number of cylinders for a car given a particular miles per gallon as follows:

\[ \textrm{E}[\textrm{cyl}|\textrm{mpg}=m] = \sum_{c \in \{4,6,8\}} c\cdot \textrm{P}(\textrm{cyl}=c|\textrm{mpg}=m) \] We can use the above formula to derive a posterior distribution for \(\textrm{E}[\textrm{cyl}|\textrm{mpg}=m]\) from the model. The model gives us a posterior distribution for \(\textrm{P}(\textrm{cyl}=c|\textrm{mpg}=m)\): when mpg = \(m\), the response-scale linear predictor (the .value column from add_fitted_draws) for cyl (aka .category) = \(c\) is \(\textrm{P}(\textrm{cyl}=c|\textrm{mpg}=m)\). Thus, we can group within .draw and then use summarise to calculate the expected value:

Now let’s do some posterior predictive checking: do posterior predictions look like the data? For this, we’ll make new predictions at the same values of mpg as were present in the original dataset (gray circles) and plot these with the observed data (colored circles):

This looks pretty good. Let’s check using another typical posterior predictive checking plot: many simulated distributions of the response (cyl) against the observed distribution of the response. For a continuous response variable this is usually done with a density plot; here, we’ll plot the number of posterior predictions in each bin as a line plot, since the response variable is discrete:

This also looks good.

Another way to look at these posterior predictions might be as a scatterplot matrix. tidybayes::gather_pairs makes it easy to generate long-format data frames suitable for creating custom scatterplot matrices (or really, arbitrary matrix-style small multiples plots) in ggplot using facet_grid:

Ordinal model with categorical predictor

Here’s an ordinal model with a categorical predictor:

## Compiling the C++ model
## recompiling to avoid crashing R session
## Start sampling

Then we can plot predicted probabilities for each outcome category within each level of the predictor:

esoph %>%
  data_grid(agegp) %>%
  add_fitted_draws(m_esoph_brm, dpar = TRUE) %>%
  ggplot(aes(x = agegp, y = .value, color = .category)) +
  stat_pointinterval(position = position_dodge(width = .4), .width = c(.66, .95), show.legend = TRUE) +
  scale_size_continuous(guide = FALSE)

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:

This output should be very similar to the output from the corresponding m_esoph_rs model in vignette("tidy-rstanarm") (modulo different priors), though brms does more of the work for us to produce it than rstanarm does.