Calc.relimp (package relaimpo) with ggplot2

I need a help to insert the calc.relimp into ggplot2. I tried to find an answer on search sites.

The basic code I find whitout ggplot is:

           model = calc.relimp(mtcars,
                               type = c("lmg","last","first","pratt"),
                               rela = TRUE)

           plot(model)

I need a help to combine calc.relimp with ggplot2.

Someone knows how to solve this problem?

Hi @diego-rods
Welcome to the Posit/RStudio Community Forum.
Sorry that there has been no earlier response to your question.

You need to access the components of the model output from {relaimpo}, create a new dataframe of the results, and then pass them into {ggplot}. The following code gets close to the default output - you can tinker with the formatting to suit your needs:

suppressPackageStartupMessages(library(tidyverse))
library(relaimpo)

# Regresses first column (mpg) against the other 10 variables
model <- calc.relimp(mtcars,
                     type = c("lmg","last","first","pratt"),
                     rela = TRUE)
plot(model)
str(model)
summary(model)

mod.df <- data.frame(lmg = model$lmg * 100,
                     first = model$first * 100,
                     last = model$last * 100,
                     pratt = model$pratt * 100)
mod.df

mod.df %>%
  rownames_to_column(var = "Variable") %>%
  pivot_longer(cols=2:5,
               names_to = "Method",
               values_to = "% of R2") %>%
  arrange(Method, Variable) -> long.df

head(long.df)

ggplot(data=long.df) +
  aes(x=Variable, y=`% of R2`) +
  geom_col() +
  facet_wrap(~ Method, nrow=2, ncol=2) +
  labs(title=(paste("Relative importances for", names(mtcars)[1])))