vincentarelbundock / marginaleffects

R package to compute and plot predictions, slopes, marginal means, and comparisons (contrasts, risk ratios, odds, etc.) for over 100 classes of statistical and ML models. Conduct linear and non-linear hypothesis tests, or equivalence tests. Calculate uncertainty estimates using the delta method, bootstrapping, or simulation-based inference
https://marginaleffects.com
Other
411 stars 44 forks source link

tinyplot support #1157

Open vincentarelbundock opened 3 weeks ago

vincentarelbundock commented 3 weeks ago

Should this be default?

Switch to ggplot2 when installed? That could be confusing, but people expect ggplot2.

grantmcdermott commented 3 weeks ago

Proof of concept fwiw...

library(marginaleffects)
library(tinyplot)

dat = read.csv("https://vincentarelbundock.github.io/Rdatasets/csv/palmerpenguins/penguins.csv")

mod = lm(body_mass_g ~ flipper_length_mm * factor(species) * bill_length_mm, data = dat)

preds = predictions(
  mod,
  newdata = datagrid(
    flipper_length_mm = 180:220,
    bill_length_mm = fivenum,
    species = unique
  )
) |>
  transform(bill_length_mm = factor(bill_length_mm, labels = c("min", "lh", "med", "uh", "max")))

with(
  preds,
  plt(
    x = flipper_length_mm,
    y = estimate,
    ymin = conf.low,
    ymax = conf.high,
    type = "ribbon",
    by = bill_length_mm,
    facet = species,
    grid = TRUE, frame = FALSE,
    palette = "classic"
  )
)

Created on 2024-07-05 with reprex v2.1.0

vincentarelbundock commented 3 weeks ago

Oh yeah, this looks really nice.

For reference, implementing this would probably be pretty easy, but there are a few different cases to consider. For example, when x-axis is categorical we want point range rather than ribbon. But all this is contained in a single function, which should be easy to port:

https://github.com/vincentarelbundock/marginaleffects/blob/main/R/plot_build.R

One potential path forward would be to support both tinyplot and ggplot2, with a global option that users can set. For example, this could check if tinyplot is installed first, then move to ggplot2:

options(marginaleffects_plot_engine = c("tinyplot", "ggplot2"))