0

My aplogies if this is a duplicate question with a possible solution elsewhere, @I_O helped me figure out how to generate check_model type of plots from a list of lm objects. Thankful to him for that.

library(patchwork)
library(performance)
library(ggplot)

data("mtcars")
head("mtcars")

the_models <- 
  split(mtcars, mtcars$cyl) |>
  Map(f = \(d) lm(mpg ~ hp + wt, data = d))

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

the_plots |> Reduce(f = `/`)

This does what it is supposed to, but I am not sure how to add title on top of each row to indicate which model the plot represents ? I have tried several options , for example , inserting a line lab( ... =names(the_models )..), labs...names(the_models)[m], none of them worked. So I am not sure how to proceed.

Expecting a plot like this

enter image description here

Any suggestion is very helpful. Thanks.

bison2178
  • 747
  • 1
  • 8
  • 22
  • @MrFlick, ah, yes. sorry about that. Updated the question now with all the relevant libraries. – bison2178 Jun 05 '23 at 14:14
  • See this existing question: https://stackoverflow.com/questions/60269293/r-package-patchwork-titles-for-rows-columns. You can use `wrap_elements` with a `grid::textGrob` to create an object you can also use in your layout. – MrFlick Jun 05 '23 at 14:25
  • @MrFlick, thanks MrFlick I will try that, would you know how to access the list names within the `Map` function, i tried `names(the_models )[m]` and that gave me an error. – bison2178 Jun 05 '23 at 15:59
  • You can't get the names from the objects being iterate over. You can pass the names as an additional vector to `Map` or you could use a function like `purrr::imap`, but wither way the inner function will have to accept two separate parameters. – MrFlick Jun 05 '23 at 16:15
  • @MrFlick, gottcha. – bison2178 Jun 05 '23 at 16:21

0 Answers0