I'm using the check_model
function within the performance library in r to check the assumptions of a simple linear regression model using lm
.
I am fitting 3 models on different subsets of the data.
data("mtcars")
head("mtcars")
table(mtcars$cyl, useNA = "ifany")
foo <- mtcars %>%
group_by(cyl) %>%
nest() %>%
mutate(model= map(data, lm(mpg ~ hp + wt, data = .))
foo %>%
{map(.$model, summary)}
I want check_model
to plot all the 6 diagnostic plots per model in one row. Which means 3 rows, 6 plots in each row, using the model summaries which is stored as a list object.
check_model(foo$model..cylinder 4)...all 6 plots in 1 row
check_model(foo$model..cylinder 6)...all 6 plots in 1 row
check_model(foo$model..cylinder 8)...all 6 plots in 1 row
Any suggestions for how to accomplish this is much appreciated. Thanks.
one approach:
cyl
(here: by split
ing and Map
ping):the_models <-
split(mtcars, mtcars$cyl) |>
Map(f = \(d) lm(mpg ~ hp + wt, data = d))
plot
ting the result of check_model
have, besides being ggplot-objects, class patchwork
, meaning that you can specify the plot_layout
(a function provided by package {patchwork}):the_plots <-
the_models |>
Map(f = \(m) check_model(m) |>
plot() +
## lay out diagnostic plots
## into 6 columns, 1 row per model:
plot_layout(6, 1)
)
Reduce
) the list of plots into one stack. With {patchwork}, you stack plots with /
:the_plots |> Reduce(f = `/`)
edit
The output for a larger number of models (= rows) may exceed the device dimensions (Error: The viewport may be too small to show this patchwork. Please make it larger.
) If you don't need live preview, you can assign the combined plots to an object and save it like so:
all_plots <- the_plots |> Reduce(f = `/`)
ggsave(all_plots, filename = 'all_plots.pdf', height = 20, width = 15)
(ggsave
can save in various raster and vector formats, guessing from the filename's extension.)