The function ggstatsplot::ggcoefstats
generates dot-and-whisker plots of regression models saved in tidy data frames (produced with the broom
package). By default, the plot displays 95%
confidence intervals for the regression coefficients. The function currently supports only those classes of object that are supported by the broom
package. For an exhaustive list, see- https://broom.tidyverse.org/articles/available-methods.html
In this vignette, we will see examples of how to use this function. We will try to cover as many classes of objects as possible. Unfortunately, there is no single dataset that will be helpful for carrying out all types of regression analyses and, therefore, we will use various datasets to explore data-specific hypotheses using regression models.
Note before: The following demo uses the pipe operator (%>%
), so in case you are not familiar with this operator, here is a good explanation: http://r4ds.had.co.nz/pipes.html
Although the statistical models displayed in the plot may differ based on the class of models being investigated, there are few aspects of the plot that will be invariant across models:
95%
is the default). The estimate can either be effect sizes (for tests that depend on the F
statistic) or regression coefficients (for tests with t
and z
statistic), etc. The function will, by default, display a helpful x-axis label that should clear up what estimates are being displayed. The confidence intervals can sometimes be asymmetric if bootstrapping was used.ggplot2
object and, thus, it can be further modified (e.g., change themes, etc.) with ggplot2
functions.In the following examples, we will try out a number of regression models and, additionally, we will also see how we can change different aspects of the plot itself.
aov
)For this analysis, let’s use the movies_long
dataset, which provides information about IMDB ratings, budget, length, MPAA ratings (e.g., R-rated, NC-17, PG-13, etc.), and genre for a number of movies. Let’s say our hypothesis is that the IMDB ratings for a movie are predicted by a multiplicative effect of the genre and the MPAA rating it got. To begin with, let’s carry out an omnibus ANOVA to see if this is the case.
# for reproducibility
set.seed(123)
# looking at the data
dplyr::glimpse(x = ggstatsplot::movies_long)
#> Observations: 2,433
#> Variables: 8
#> $ title <fct> Shawshank Redemption, The, Lord of the Rings: The Retur...
#> $ year <int> 1994, 2003, 2001, 2002, 1994, 1993, 1977, 1980, 1968, 2...
#> $ length <int> 142, 251, 208, 223, 168, 195, 125, 129, 158, 135, 93, 1...
#> $ budget <dbl> 25.0, 94.0, 93.0, 94.0, 8.0, 25.0, 11.0, 18.0, 5.0, 3.3...
#> $ rating <dbl> 9.1, 9.0, 8.8, 8.8, 8.8, 8.8, 8.8, 8.8, 8.7, 8.7, 8.7, ...
#> $ votes <int> 149494, 103631, 157608, 114797, 132745, 97667, 134640, ...
#> $ mpaa <fct> R, PG-13, PG-13, PG-13, R, R, PG, PG, PG-13, R, PG, R, ...
#> $ genre <fct> Drama, Action, Action, Action, Drama, Drama, Action, Ac...
# plot
ggstatsplot::ggcoefstats(
x = stats::aov(
formula = rating ~ mpaa * genre,
data = ggstatsplot::movies_long
),
effsize = "omega", # changing the effect size estimate being displayed
point.color = "red", # changing the point color
point.size = 4, # changing the point size
point.shape = 15, # changing the point shape
title = "omnibus ANOVA"
) +
# further modification with the ggplot2 commands
# note the order in which the labels are entered
ggplot2::scale_y_discrete(labels = c("MPAA", "Genre", "Interaction term")) +
ggplot2::labs(x = "effect size estimate (partial omega-squared)",
y = NULL)
As this plot shows, there is no interaction effect between these two factors.
Note that we can also use this function for model selection. Let’s try out different models and see how the AIC, BIC, and log-likelihood values change.
library(ggstatsplot)
# for reproducibility
set.seed(123)
# plot
ggstatsplot::combine_plots(
# model 1
ggstatsplot::ggcoefstats(
x = stats::aov(formula = rating ~ mpaa,
data = ggstatsplot::movies_long),
title = "1. Only MPAA ratings"
),
ggstatsplot::ggcoefstats(
x = stats::aov(formula = rating ~ genre,
data = ggstatsplot::movies_long),
title = "2. Only genre"
),
ggstatsplot::ggcoefstats(
x = stats::aov(formula = rating ~ mpaa + genre,
data = ggstatsplot::movies_long),
title = "3. Additive effect of MPAA and genre"
),
ggstatsplot::ggcoefstats(
x = stats::aov(formula = rating ~ mpaa * genre,
data = ggstatsplot::movies_long),
title = "4. Multiplicative effect of MPAA and genre"
),
title.text = "Model selection using ggcoefstats",
labels = c("(a)", "(b)", "(c)", "(d)")
)
Looking at the model diagnostics, we can see that the model with only genre
as the predictor of ratings seems to perform almost equally well as more complicated additive and multiplicative models. Although there is certainly some improvement with additive and multiplicative models, it is by no means convincing enough (e.g., AIC improves by a mere 0.09%
) for us to abandon a simpler model. This insight can also be garnered by just looking at the effect sizes, which also tell us that which genre the movie belongs to seems to account for the largest variance.
lm
)Now that we have figured out that the movie genre
best explains a fair deal of variation in how good people rate the movie to be on IMDB. Let’s run a linear regression model to see how different types of genres compare with each other-
# let's check all the levels for the genre variable
levels(ggstatsplot::movies_long$genre)
#> [1] "Action" "Animation" "Comedy" "Documentary" "Drama"
#> [6] "Romance"
# plot
ggstatsplot::ggcoefstats(
x = stats::lm(
formula = rating ~ genre,
data = ggstatsplot::movies_long
),
conf.level = 0.99, # changing the confidence levels for confidence intervals
sort = "ascending", # sorting the terms of the model based on estimate values
label.direction = "both", # direction in which to adjust position of labels (both x and y)
ggtheme = ggplot2::theme_gray(), # changing the default theme
stats.label.color = c("#CC79A7", "darkgreen", "#0072B2", "black", "red"),
title = "Movie ratings by their genre",
subtitle = "Source: www.imdb.com"
) +
# further modification with the ggplot2 commands
# note the order in which the labels are entered
ggplot2::scale_y_discrete(labels = c("Comedy", "Romance", "Documentary", "Animation", "Drama")) +
ggplot2::labs(y = "genre (comparison level: Action)") +
ggplot2::theme(axis.title.y = ggplot2::element_text(size = 14, face = "bold"))
As can be seen from the regression coefficients, compared to the action movies, only romantic movies, animated movies, and dramas fare better with the audiences.
lmer
)Now let’s say we want to see how movie’s budget relates to how good the movie is rated to be on IMDB (e.g., more money, better ratings?). But we have reasons to believe that the relationship between these two variables might be different for different genres (e.g., budget might be a good predictor of how good the movie is rated to be for animations or actions movies as more money can help with better visual effects and animations, but this may not be true for dramas; also see the ggscatterstats
vignette), so we don’t want to use stats::lm
. In this case, therefore, we will be running a linear mixed-effects model (using lme4::lmer
and p-values generated using the lmerTest
package) with a random slope for the genre variable.
library(lme4)
library(ggstatsplot)
# combining the two different plots
ggstatsplot::combine_plots(
# model 1: simple linear model
ggstatsplot::ggcoefstats(
x = stats::lm(
formula = scale(rating) ~ scale(budget),
data = ggstatsplot::movies_long
),
title = "linear model",
exclude.intercept = FALSE # show the intercept
) +
ggplot2::labs(x = parse(text = "'standardized regression coefficient' ~italic(beta)")),
# model 2: linear mixed-effects model
ggstatsplot::ggcoefstats(
x = lme4::lmer(
formula = rating ~ budget + (budget | genre),
data = ggstatsplot::movies_long,
control = lme4::lmerControl(calc.derivs = FALSE)
),
title = "linear mixed-effects model",
exclude.intercept = FALSE, # show the intercept
effects = "fixed" # show both fixed and random effects
) +
ggplot2::labs(x = parse(text = "'standardized regression coefficient' ~italic(beta)"), y = "fixed effects"),
labels = c("(a)", "(b)"),
nrow = 2,
ncol = 1,
title.text = "Relationship between movie budget and its IMDB rating"
)
As can be seen from these plots, although there seems to be a really small correlation between budget and rating in a linear model, this effect is not significant once we take into account the hierarchical structure of the data.
nls
)So far we have been assuming a linear relationship between movie budget and rating. But what if we want to also explore the possibility of a non-linear relationship? In that case, we can run a non-linear least squares regression. Note that you need to choose some non-linear function, which will be based on prior exploratory data analysis (y ~ k/x + c
implemented here, but you can try out other non-linear functions, e.g. Y ~ k * exp(-b*c)
).
library(ggstatsplot)
# plot
ggstatsplot::ggcoefstats(
x = stats::nls(
formula = rating ~ k / budget + c, # try toying around with the form of non-linear function
data = ggstatsplot::movies_long,
start = list(k = 1, c = 0)
),
title = "Non-linear relationship between budget and rating",
subtitle = "Source: IMDB"
)
This analysis shows that there is indeed a possible non-linear association between rating and budget (non-linear regression term k
is significant), at least with the particular non-linear function we used.
glm
)In all the analyses carried out thus far, the outcome variable (y
in y ~ x
) has been continuous. In case the outcome variable is nominal/categorical/factor, we can use the generalized form of linear model that works even if the response is a numeric vector or a factor vector, etc.
To explore this model, we will use the Titanic dataset, which tabulates information on the fate of passengers on the fatal maiden voyage of the ocean liner Titanic, summarized according to economic status (class), sex, age, and survival. Let’s say we want to know what was the strongest predictor of whether someone survived the Titanic disaster-
library(ggstatsplot)
# having a look at the Titanic dataset
df <- as.data.frame(x = Titanic)
str(df)
#> 'data.frame': 32 obs. of 5 variables:
#> $ Class : Factor w/ 4 levels "1st","2nd","3rd",..: 1 2 3 4 1 2 3 4 1 2 ...
#> $ Sex : Factor w/ 2 levels "Male","Female": 1 1 1 1 2 2 2 2 1 1 ...
#> $ Age : Factor w/ 2 levels "Child","Adult": 1 1 1 1 1 1 1 1 2 2 ...
#> $ Survived: Factor w/ 2 levels "No","Yes": 1 1 1 1 1 1 1 1 1 1 ...
#> $ Freq : num 0 0 35 0 0 0 17 0 118 154 ...
# plot
ggstatsplot::ggcoefstats(
x = stats::glm(
formula = Survived ~ Sex + Age,
data = df,
weights = df$Freq, # vector containing weights (no. of observations per row)
family = "binomial"
),
exponentiate = TRUE,
ggtheme = ggplot2::theme_dark(),
vline.color = "red",
vline.linetype = "solid",
label.segment.color = "red",
stats.label.size = 3.5,
stats.label.color = c("orangered",
"dodgerblue")
)
As can be seen from the regression coefficients, all entered predictors were significant predictors of the outcome. More specifically, being a female was associated with higher likelihood of survival (compared to male). On other hand, being an adult was associated with decreased likelihood of survival (compared to child).
glmer
)In the previous example, we saw how being a female and being a child was predictive of surviving the Titanic disaster. But in that analysis, we didn’t take into account one important factor: the passenger class in which people were traveling. Naively, we have reasons to believe that the effects of sex and age might be dependent on the class (maybe rescuing passengers in the first class were given priority?). To take into account this hierarchical structure of the data, we can run generalized linear mixed effects model with a random slope for class.
# plot
ggstatsplot::ggcoefstats(
x = lme4::glmer(
formula = Survived ~ Sex + Age + (Sex + Age | Class),
data = df,
weights = df$Freq,
# vector containing weights (no. of observations per row)
family = "binomial",
control = lme4::glmerControl(
optimizer = "Nelder_Mead",
calc.derivs = FALSE,
boundary.tol = 1e-7
)
),
exponentiate = TRUE
)
As we had expected, once we take into account the differential relationship that might exist between survival and predictors across different passenger classes, only the sex factor remain a significant predictor (also see the ggspiestats
vignette where we had explored this dataset). In other words, being a female was the strongest predictor of whether someone survived the tragedy that befell the Titanic.
This vignette was supposed to give just a taste for only some of the regression models supported by ggcoefstats
. The full list of supported models will keep expanding as additional tidiers are added to the broom
package: https://broom.tidyverse.org/articles/available-methods.html
Note that not all models supported by broom
will be supported by ggcoefstats
. In particular, classes of objects for which there is:
lmRob
, glmRob
, etc.)kmeans
)will not be supported. That said, some of these models might be supported in future.
If you find any bugs or have any suggestions/remarks, please file an issue on GitHub: https://github.com/IndrajeetPatil/ggstatsplot/issues