rggplot2customizationshapbeeswarm

How to customize shapviz plots?


I'm a recent user of the {shapviz} package and I'm having some difficulties customizing the graphs (like the importance graph).

I would like, for example:

Since shapviz plots are of the ggplot type, I tried to change them by accessing the lists or adding layers, but I was unsuccessful.

Thanks!


Solution

  • Using some toy data, here's how you could change those aesthetics:

    library(xgboost)
    library(shapviz)
    library(viridis)
    library(ggplot2)
    
    # Toy data
    X_train <- data.matrix(iris[, -1])
    dtrain <- xgb.DMatrix(X_train, label = iris[, 1], nthread = 1)
    fit <- xgb.train(data = dtrain, nrounds = 10, nthread = 1)
    x <- shapviz(fit, X_pred = X_train)
    
    # Modify shapviz plot
    p <- sv_importance(x, kind = "both", show_numbers = TRUE, fill = "red") +
      scale_colour_gradient(
        low = "darkblue", high = "skyblue",
        breaks = c(0, 1), labels = c("low", "high")
      ) +
      labs(colour = "My Title") +
      theme(
        legend.key.size = unit(2, "cm"),
        legend.title.position = "right",
        legend.title = element_text(angle = 90, hjust = 0.5)
      )
    
    # Add geom_label and remove the geom_text
    p2 <- p +
      geom_label(aes(x, y, label = label), data = layer_data(p, 4), fontface = "italic")
    
    p2$layers[[4]] <- NULL
    
    p2
    

    Created on 2024-04-08 with reprex v2.1.0