library(tidyverse)
library(marginaleffects) # generating and visualising model predictions
library(sjPlot) # visualising model predictions
library(apaTables) # OLS regression tables
library(modelsummary) # more flexible regression tables
# read the raw data
troy_data <- read_csv("data/Troy_replication.csv")
# process the data for analysis
troy_scales <- troy_data %>%
filter(consent == "Y") %>% # only people who consented
drop_na(socioeconomic_status:LS_4) %>% # remove missing data from key variables
rowwise() %>% # apply functions row by row for scale score
mutate(CRA_sum = sum(c_across(CRA_1:CRA_8)), # sum for CRA
LS_mean = mean(c_across(LS_1:LS_4)), # mean for life stress
DS_sum = sum(c_across(DS_1:DS_5))) %>% # sum for depression
ungroup() %>% # stop appling rowwise
mutate(CRA_centre = CRA_sum - mean(CRA_sum), # centre variables for interactions
LS_centre = LS_mean - mean(LS_mean),
SES_centre = socioeconomic_status - mean(socioeconomic_status))7 Visualising Model Estimates
In this chapter, we take regression models and demonstrate all the ways you can visualise them to your reader. A major limitation in psychology articles is that reporting typically stops at producing a table of regression coefficients. This can be useful for summarising a bunch of values, but it is does not help communicate the overall results, particularly when you get to more complex research where raw regression coefficients are not super intuitive. The other chapters in this book demonstrate building and interpreting general linear models, so we only focus on visualisation in this chapter.
Chapter Intended Learning Outcomes (ILOs)
By the end of this chapter, you will be able to:
Recognise the difference between visualising raw data and complex model estimates and uncertainty.
Use the
sjPlot package to quickly visualise model predictions.Use the
marginaleffects package to visualise or generate model predictions.
7.1 Organising your files and project for the chapter
To keep your work organised for this course, we recommend creating a folder on your computer for the course, then a separate sub-folder for assessments and each chapter of the book. Within each sub-folder, create folders for data and figures, so you have somewhere memorable to save the files and you know where everything is.
In your folder for statistics and research design
Stats_Research_Design, create a new folder called07_visualise_regression. Within07_visualise_regression, create two new folders calleddataandfigures.Create an R Project for
07_visualise_regressionas an existing directory for your chapter folder. This should now be your working directory.Create a new Quarto/RMarkdown document and give it a sensible title describing the chapter, such as
07 Visualising Regression Modelsand save the file in your07_visualise_regressionfolder.In this chapter, we are working with a few datasets, so we will explain them briefly as we get to them. Please save the following data files: Troy_replication.csv and Bostyn_2018.csv. Right click the links and select “save link as”, or clicking the link will save the files to your Downloads. Make sure that you save the file as “.csv”. Save or copy the file to your
data/folder within07_visualise_regression.
You are now ready to start working on the chapter!
7.2 Visualising OLS regression models
This demonstration builds on Chapters 1-3 for ordinary least square (OLS) regression models you will be most familiar with. We are taking simple or multiple linear regression models and visualising the estimates/predictions.
For this section, you will analyse data from a replication of Troy et al. (2017) study 1 that James conducted with two students. They were interested in the connection between emotion regulation, socioeconomic status, and depression symptoms. In the original study, they collected data in the USA. In the replication, they collected data from participants in the UK and Malaysia.
The key analysis built a multiple linear regression model with depression symptoms as the outcome, and predictors of life stress and an interaction between socioeconomic status and cognitive reappraisal ability. We will work with this analysis to explore how we can visualise different predictors/estimates from the model.
We will not use them all but the codebook for the data files explains all the variables:
| Variable | Description |
|---|---|
user_id |
Numerical participant ID number. |
consent |
Do you consent to take part in this study? Yes (Y) or No (N). |
gender |
Gender with three categories: Male (M), Female (F), I would rather not answer (NA). |
nationality |
Do you currently reside in Malaysia / UK? Participants saw Malaysia or UK depending on the study, and answered Yes (Y) or No (N). |
age |
Age in years. |
race |
Race with four options for the UK version (White (W), Asian/Asian British (A), Black/African/Caribbean/Black British (B), Other (O)) and four options for the Malaysian version (Malay (M), Chinese (C), Indian (I), Other (O)). |
socioeconomic_status |
Current annual family income, rated on a 1 (“$10,000 or below”) to 12 (“$200,000 or above”) scale. In this study, participants saw converted amounts in UK Pounds or Malaysian Ringgits. |
CRA_1 to CRA_8
|
8-item version of the Emotion Regulation Questionnaire for cognitive reappraisal ability. Responses range from 1 to 7. |
HCRU_1 to HCRU_6
|
6-items for the reappraisal subscale of the Emotion Regulation Questionnaire. Responses range from 1 to 7. |
DS_1 to DS_5
|
5-item version of the Center for Epidemiologic Studies Depression Scale. Responses range from 0 to 3. |
LS_1 to LS_4
|
4-item version of the Perceived Stress Scale. Responses range from 1 to 5. |
country |
Whether the participant is from the UK or Malaysia data. |
7.2.1 Read and wrangle the data
For this chapter, we are focusing on visualising the model predictions. So, we provide the code for wrangling the data in preparation for the analysis. If you do not have any of the packages, make sure you install them first.
7.2.2 One predictor
As a starting point, we will create a simple linear regression model, just using life stress as it is (spoiler) the only significant predictor. We can see here that life stress is a significant positive predictor, we expect higher depression scores for those experiencing greater life stress.
Call:
lm(formula = DS_sum ~ LS_mean, data = troy_scales)
Residuals:
Min 1Q Median 3Q Max
-6.6117 -2.1552 -0.4583 1.9458 8.0226
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) -1.6952 0.9310 -1.821 0.0703 .
LS_mean 2.0767 0.3079 6.746 1.96e-10 ***
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Residual standard error: 3.067 on 182 degrees of freedom
Multiple R-squared: 0.2, Adjusted R-squared: 0.1956
F-statistic: 45.5 on 1 and 182 DF, p-value: 1.96e-10
7.2.2.1 ggplot
We can use geom_smooth() layer applies a regression line with 95% confidence interval band. If you only have a simple linear regression model, you would be totally justified only using this method.
7.2.2.2 sjPlot
For quickly plotting model predictions, the plot_model() function which takes a linear model object.
To plot the model predictions, we must specify the “pred” type and pass the term for which predictor we want to plot. For the simple model here, there is only option but you must set it anyway and you can see how this applies to more complex models later. Usefully, both
plot_model(troy_simple,
type = "pred", # predicted/marginal effects
terms = "LS_mean", # specify predictor
show.data = TRUE) + # show the data
theme_classic() +
labs(x = "Mean Life Stress",
y = "Sum Depressive Score") +
scale_y_continuous(limits = c(0, 15), # plot the full depression scale
breaks = seq(0, 15, 3))
7.2.2.3 marginaleffects
Finally, we can produce the exact same output using the plot_model() from condition and add data points through adding some transparency. We can also add our customisation layers via ggplot2 code.
7.2.3 Multiple predictors
Now that we have the basic building blocks for the plotting functions, we can scale things up to visualise multiple linear regression models. This is where we are really going to benefit from packages like
Call:
lm(formula = DS_sum ~ LS_mean + CRA_sum * socioeconomic_status,
data = troy_scales)
Residuals:
Min 1Q Median 3Q Max
-7.006 -2.002 -0.468 1.924 8.516
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 1.847662 2.224026 0.831 0.407
LS_mean 1.819543 0.320715 5.673 5.54e-08 ***
CRA_sum -0.065887 0.044232 -1.490 0.138
socioeconomic_status -0.114707 0.334156 -0.343 0.732
CRA_sum:socioeconomic_status 0.001296 0.008154 0.159 0.874
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Residual standard error: 3.034 on 179 degrees of freedom
Multiple R-squared: 0.23, Adjusted R-squared: 0.2128
F-statistic: 13.37 on 4 and 179 DF, p-value: 1.492e-09
The effects do not quite replicate here where we still get a significant positive predictor of life stress, but the individual and interaction effects of the other predictors are not statistically significant. Visualising this model presents us with two demonstration opportunities: how the coefficients are now partial effects and plotting interaction effects.
As we included an interaction term in the model, one thing we must be very careful about is how we code our predictors. A common oversight is how the coefficients now represent simple effects (the effect of one predictor for a given level of another predictor) and not main effects (the effect of one predictor when all the other predictors are held constant).
This is critical for interpreting the model coefficients but not visualising the model. The actual relationships are the same regardless of the coding scheme, so it does not change anything about plotting the predictions. The authors of
7.2.3.1 Partial effects
The first is that we can demonstrate pulling out individual predictors from a multiple regression model. Compared to the plot above, all we need to do is use the full model object name troy_full, and the other predictors are the same.
The reason is it important to use the model predictions to visualise your results is that the coefficients now represent partial effects, and they depend on other predictors in the model. Sometimes there will be little difference, other times you will get drastically different results where signs could flip or significant effects become non-significant. This means it is critical to visualise the effects from the model you want to communicate to your reader.
To demonstrate this, we can plot the predictions from both models. The example here is quite subtle, but if you look at the model output, the effect is weaker in the multiple regression model compared to the simple model. The plot relies on working with
Show me the code
# marginal effects for the simple model
pred_one <- avg_predictions(troy_simple,
variables = "LS_mean")
# marginal effects for the multiple model
pred_multiple <- avg_predictions(troy_full,
variables = "LS_mean")
# save two colours from viridis
colours <- c("#420A68FF", "#F3771AFF")
# compare model predictions
ggplot() +
geom_point(data = troy_scales,
aes(x = LS_mean, y = DS_sum)) +
# simple prediction
geom_line(data = pred_one, # plot estimate line
aes(x = LS_mean, y = estimate),
color = colours[1]) +
geom_ribbon(data = pred_one, # plot confidence interval band
aes(x = LS_mean,
ymin = conf.low, ymax = conf.high),
alpha = .2,
fill = colours[1]) +
# multiple prediction
geom_line(data = pred_multiple,
aes(x = LS_mean, y = estimate),
color = colours[2]) +
geom_ribbon(data = pred_multiple,
aes(x = LS_mean,
ymin = conf.low, ymax = conf.high),
alpha = .2,
fill = colours[2]) +
theme_classic() +
annotate(geom = "text", # add annotation for simple model
x = 5.4,
y = 8.7,
label = "Simple Model",
colour = colours[1]) +
annotate(geom = "text", # add annotation for multiple model
x = 5.4,
y = 8.1,
label = "Multiple Model",
colour = colours[2]) +
labs(x = "Mean Life Stress",
y = "Sum Depressive Score") +
coord_cartesian(xlim = c(1, 5.5), # expand plot to avoid text cutting off
clip = "off")
7.2.3.2 Interaction effects
The other key demonstration here is being able to plot interaction effects. Interactions are super tricky to interpret just from the model coefficient, meaning plotting your estimates will really help both you and your reader understand your key results. For interactions containing at least one categorical predictor, this is relatively simple. You can plot the effects either as individual groups, or how the slope of one variable differs by each group. For continuous by continuous interactions, they need some trickery.
In the original Troy et al. article, they plot simple slopes, where you artificially create groups for continuous data. This is typically standard deviations around the mean. They plot one SD below and above the mean for each predictor. We can recreate their plot to explore the interaction in a few steps:
- Calculate the values 1 SD above and below the mean for CRA and socioeconomic status.
# Step 1: calculate values
# Calculate CRA 1 SD above and below mean
CRA_1SD_below <- mean(troy_scales$CRA_sum) - sd(troy_scales$CRA_sum)
CRA_1SD_above <- mean(troy_scales$CRA_sum) + sd(troy_scales$CRA_sum)
# Calculate SES 1 SD above and below mean
socio_1SD_below = mean(troy_scales$socioeconomic_status) - sd(troy_scales$socioeconomic_status)
socio_1SD_above = mean(troy_scales$socioeconomic_status) + sd(troy_scales$socioeconomic_status)- Use these values to generate marginal effects from the model object.
# Step 2: calculate simple slopes using marginal effects
simple_slopes <- avg_predictions(troy_full,
by = c("CRA_sum", "socioeconomic_status"),
newdata = datagrid(CRA_sum = c(CRA_1SD_below, # SD above and below from above
CRA_1SD_above),
socioeconomic_status = c(socio_1SD_below,
socio_1SD_above)))
simple_slopes
CRA_sum socioeconomic_status Estimate Std. Error z Pr(>|z|) S 2.5 %
28.2 1.23 5.23 0.519 10.08 <0.001 77.0 4.21
28.2 6.86 4.79 0.437 10.97 <0.001 90.6 3.93
48.4 1.23 3.94 0.449 8.77 <0.001 58.9 3.06
48.4 6.86 3.64 0.437 8.34 <0.001 53.6 2.79
97.5 %
6.25
5.64
4.81
4.50
Type: response
- Use the estimate and 95% confidence interval from the marginal effects to create a plot.
# Step 3: plot the simple slopes values
simple_slopes %>%
mutate(CRA_sum = as.factor(CRA_sum), # treat number as factor
socioeconomic_status = as.factor(socioeconomic_status)) %>%
ggplot(aes(x = CRA_sum,
y = estimate,
colour = socioeconomic_status,
group = socioeconomic_status)) + # connect the lines
geom_pointrange(aes(ymin = conf.low, ymax = conf.high), # estimate and 95% CI
position = position_dodge(0.1)) + # avoid overlap
geom_line(position = position_dodge(0.1)) +
scale_x_discrete(name = "Cognitive Reappraisal",
labels = c("Low CRA", "High CRA")) +
scale_y_continuous(name = "Depressive Symptoms",
limits = c(0, 8),
breaks = seq(0, 8, 2)) +
scale_colour_discrete(name = "Socioeconomic Status",
labels = c("Low SES", "High SES"),
palette = colours) + # reuse colours from earlier
theme_classic()
7.2.3.3 sjPlot
The beauty of the
For example, we can quickly plot the partial effect of life stress as a significant positive predictor of depressive symptoms. Remember this is immediately from the plotting function but you can add ggplot2 layers to customise it further.
Alternatively, you can plot simple slopes by including two continuous predictors in the terms argument. In the
7.3 Visualising generalised linear regression models
Now that we have demonstrated the logic behind plotting estimates and uncertainty from simple and multiple linear regression models, the next step is showing how this applies to more complex models. One of the benefits of this linear models approach is that when you have a non-normal outcome, you can switch the distribution family to honour the data generating process, but the rest of the model logic remains pretty much the same. For this demonstration, we will work with logistic regression models when you have a binary outcome. This builds on the content from Chapters 5 and 6.
The data are the same as the standalone logistic regression chapter, but as a reminder, Bostyn et al. studied the classic trolley-dilemma in moral philosophy. In the typical format, a trolley (streetcar/tram) is travelling along tracks and will run over five people. However, you have the choice to pull a lever and divert the trolley to run over just one person. Although this would save lives, you must manually intervene to essentially kill one person. This is typically always a hypothetical scenario as it’s difficult to ask an ethics board for permission to run over people. In this study, Bostyn et al. compared a hypothetical version of the trolley-dilemma with a (seemingly) realistic version. Participants chose between not intervening and allowing five mice in a cage to be shocked with electricity or they could intervene and one mouse would be shocked instead.
They had two main research questions:
Is there a difference in moral decision-making when participants completed a hypothetical compared to a real version of the trolley-dilemma task?
Would participants’ moral preferences predict their response on the trolley-dilemma task?
Before we get started, we need to read in the data and apply a few wrangling steps.
bostyn_data <- read_csv("data/Bostyn_2018.csv") %>%
select(STUDY:DECISION, DEO, CON) %>% # just select first four variables
drop_na(DECISION) %>%
mutate(study = factor(STUDY,
levels = c(1, 2),
labels = c("Real", "Hypothetical")),
label = factor(DECISION,
levels = c(0, 1),
labels = c("DEO", "CON")),
GENDER = as.factor(GENDER))7.3.1 One predictor
The first analysis from Bostyn et al. is exploring whether the decision to make a consequentialist decision (intervening to shock the poor single mouse) is more likely in the real or hypothetical scenario. We have one outcome and one predictor, but we need to fit a generalised linear regression model to work with the dichotomous outcome.
Call:
glm(formula = DECISION ~ study, family = binomial(link = "logit"),
data = bostyn_data)
Coefficients:
Estimate Std. Error z value Pr(>|z|)
(Intercept) 1.8539 0.2109 8.790 <2e-16 ***
studyHypothetical -0.7713 0.3290 -2.344 0.0191 *
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
(Dispersion parameter for binomial family taken to be 1)
Null deviance: 251.53 on 274 degrees of freedom
Residual deviance: 246.17 on 273 degrees of freedom
AIC: 250.17
Number of Fisher Scoring iterations: 4
If you are unfamiliar with logistic regression models, make sure you check out the standalone chapter. For a brief summary though, the estimates are no longer raw units, they are logits or log odds (statistical trickery to fit straight lines). The study predictor is statistically significant and negative, showing there are lower log odds of making a consequentialist decision in the real scenario (the reference group) compared to the hypothetical scenario (the target group). Log odds are nasty to interpret though, so taking the exponential converts it to an odds ratio.
Odds ratios below 1 break by brain, so I prefer to take the reciprocal to turn it into a number easier to understand.
So, the odds of making a consequentialist decision are 2.16 times higher in the real scenario compared to the hypothetical scenario, i.e., people are more likely to intervene in a real scenario.
Odds ratios can also be a little awkward to understand, so the final step - and where plotting comes in - is by following the quantities of interest approach. For dichotomous outcomes, the estimates that are easiest to communicate to a wider audience are probabilities.
This is known as the response scale rather than the link scale. The other chapter demonstrates how to calculate this manually, but we can plot the probabilities as the default option in marginaleffects is to use the response scale. Note this is a little truncated, but applying the full 0 to 1 (0 to 100%) scale has way too much white space.
7.3.2 Multiple predictors
The next analysis Bostyn et al. report is a larger model predicting the decision of intervening by adding measures of consequentialist reasoning, deontological reasoning, gender, and age. Oddly (something I address in the next section), they apply this model twice: one for the real scenario and one for the hypothetical scenario.
Call:
glm(formula = DECISION ~ CON + DEO + GENDER + AGE, family = binomial(link = "logit"),
data = filter(bostyn_data, study == "Real"))
Coefficients:
Estimate Std. Error z value Pr(>|z|)
(Intercept) -3.01851 4.87718 -0.619 0.5360
CON 0.30102 0.36194 0.832 0.4056
DEO -0.69796 0.39985 -1.746 0.0809 .
GENDER1 -0.03272 0.47864 -0.068 0.9455
AGE 0.31225 0.25391 1.230 0.2188
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
(Dispersion parameter for binomial family taken to be 1)
Null deviance: 152.28 on 191 degrees of freedom
Residual deviance: 146.63 on 187 degrees of freedom
AIC: 156.63
Number of Fisher Scoring iterations: 5
They were particularly interested in the effect of consequentialist reasoning, which was not a statistically significant predictor of whether someone intervenes or not. In a logistic regression model, continuous predictors can be particularly tricky to interpret in isolation. Remember the interpretation is how the outcome changes for every one unit change. If the scale of the continuous predictor is large, the change in predicted probability can be tiny. It is not so much of an issue here as the predictor ranges between 1 and 5 (it is the mean of 10 scenarios on a 1-5 scale), but it is another benefit of using this marginal effects and quantity of interest approach. You can see this on the response scale for how the predicted probability changes across the scale points.

This reinforces the model coefficients where consequentialist reasoning is a non-significiant predictor of intervening or not, at least for those in the real scenario.
7.3.3 Interactions
As a final demonstration, this is not something Bostyn et al. reported but addresses a quirk of their analysis approach. They fit one version of the model for everyone in the real scenario group and one for everyone in the hypothetical scenario group. Consequentialist reasoning is significant in the hypothetical group but not in the real group.
For me, this is an interaction fallacy rather than directly comparing the two groups. I will add in an interaction between consequentialist reasoning and the study scenario. This model does not use centered/deviation-coded predictors as we are focusing on visualisation, so be careful interpreting the model coefficients for single predictors.
Call:
glm(formula = DECISION ~ CON * study + DEO + GENDER + AGE, family = binomial(link = "logit"),
data = bostyn_data)
Coefficients:
Estimate Std. Error z value Pr(>|z|)
(Intercept) -3.4421 3.8478 -0.895 0.371
CON 0.2887 0.3467 0.833 0.405
studyHypothetical -2.0297 1.4408 -1.409 0.159
DEO -0.4439 0.2929 -1.516 0.130
GENDER1 0.1757 0.4042 0.435 0.664
AGE 0.2981 0.1976 1.508 0.131
CON:studyHypothetical 0.4227 0.4965 0.851 0.395
(Dispersion parameter for binomial family taken to be 1)
Null deviance: 251.53 on 274 degrees of freedom
Residual deviance: 233.97 on 268 degrees of freedom
AIC: 247.97
Number of Fisher Scoring iterations: 5
Importantly, there is not a significant interaction, but to see what this looks like, it is critical to visualise it.

This hints at the Bostyn et al. results where the effect in the hypothetical group is much stronger (the slope is steeper) but when we include it as an interaction, that difference in slope between the two groups is not statistically significant.
7.4 Other useful visualisation techniques
In this chapter, I have made the case that visualising model predictions is really going to help communicate your results. First to you in understanding potentially complex model coefficients. Second to your reader in moving beyond reporting whether a single model coefficient is just positive or negative. However, it is valuable to report your model results and you can visualise all your coefficents in a blob plot / blobbogram for more of an overall summary.
7.4.1 Coefficient tables
One useful function is being able to report your regression model reproducibly in a report or dissertation. There are a few packages to help with this and it avoids copying and pasting values every time you want to update a model.
One useful function comes from the
Table 1
Regression results using DS_sum as the criterion
Predictor b b_95%_CI sr2 sr2_95%_CI
(Intercept) 1.85 [-2.54, 6.24]
LS_mean 1.82** [1.19, 2.45] .14 [.05, .23]
CRA_sum -0.07 [-0.15, 0.02] .01 [-.02, .03]
socioeconomic_status -0.11 [-0.77, 0.54] .00 [-.01, .01]
CRA_sum:socioeconomic_status 0.00 [-0.01, 0.02] .00 [-.00, .00]
Fit
R2 = .230**
95% CI[.12,.32]
Note. A significant b-weight indicates the semi-partial correlation is also significant.
b represents unstandardized regression weights.
sr2 represents the semi-partial correlation squared.
Square brackets are used to enclose the lower and upper limits of a confidence interval.
* indicates p < .05. ** indicates p < .01.
It will not run in this book but you can then save the table as a Word file which you can copy and paste into a document and apply minor editing.
The only downside to this is that it cannot handle anything other than OLS regression models. So, it would not work for the Bostyn et al. models. Instead, you would need something like the
| (1) | |
|---|---|
| (Intercept) | -3.442 |
| (3.848) | |
| CON | 0.289 |
| (0.347) | |
| studyHypothetical | -2.030 |
| (1.441) | |
| DEO | -0.444 |
| (0.293) | |
| GENDER1 | 0.176 |
| (0.404) | |
| AGE | 0.298 |
| (0.198) | |
| CON × studyHypothetical | 0.423 |
| (0.496) | |
| Num.Obs. | 275 |
| AIC | 248.0 |
| BIC | 273.3 |
| Log.Lik. | -116.985 |
| F | 2.657 |
| RMSE | 0.36 |
And you can export the table into a Word document by using the output argument.
7.4.2 Blobbograms
Finally, one useful way to visualising all of your model coefficients is through a forest plot, also known as blobbograms or blob plots. We can use
These can be useful if you have coefficients on a similar scale but like this example on the full Troy et al. model, the estimates and confidence intervals can be difficult to combine.
There are other ways of doing this, but I am trying to avoid keep adding more packages. For example, you have the






