florianhartig / DHARMa

Diagnostics for HierArchical Regession Models
http://florianhartig.github.io/DHARMa/
200 stars 21 forks source link

Is there a way to directly access or export the plot returned by plotResiduals()? #395

Closed smsfrn closed 7 months ago

smsfrn commented 7 months ago

I'm likely missing something obvious, but the plot itself doesn't appear to be a component in the returned object, so I'm having trouble accessing it to save programmatically. Any ideas?

smsfrn commented 7 months ago

This works for saving one-off plots, but I'm still hoping to access the plot directly from the plotResiduals() object to support more complex workflows (i.e. looping through multiple predictors, saving the residual plot for each in a list, and generating a gridded figure with all the plots).

library(tidyverse)
library(lme4)
library(DHARMa)
library(here)

dat <- iris %>%
  mutate(Petal.Length_factor = ifelse(Petal.Length < 4.2, "A", "B"))

mod <- lme4::lmer(Sepal.Width ~ Species + Petal.Width + (1 | Petal.Length_factor),
                  data = dat)

simulationOutput <- simulateResiduals(fittedModel = mod)

var <- "Petal.Width"

output_path <- here(paste0("residual_plot_", var, ".png"))

png(output_path)
plotResiduals(simulationOutput, dat %>% pull(var))
dev.off()
florianhartig commented 7 months ago

Hello Sam,

can you give me an example of another plotting function where this works?

Note that DHARMa is using base R and and not ggplot for plotting

Best, F

smsfrn commented 7 months ago

Oops, nope. I misremembered what could be done with base graphics. I'll close this!