Skip to content

Suggested improvments to plot_*() functions #1644

@mattansb

Description

@mattansb

Some thoughts for improving the current default behavior of the plot_*() functions' construction of ggplots. I would be happy to make a PR for any of these you find appropriate.

1. Use default aes()

Currently plot_build() specifies the aesthetics for each layer separately instead of setting them globally for the plot. This means that instead of writing something like:

plot_predictions(mod, condition = c("wt", "hp")) +
  geom_point(aes(y = mpg), data = mtcars)

We need to write out

plot_predictions(mod, condition = c("wt", "hp")) +
  geom_point(aes(wt, mpg, color = hp), data = mtcars)

# or:
plot_predictions(mod, condition = c("wt", "hp")) +
  aes(wt, color = hp, fill = hp) +
  geom_point(aes(y = mpg), data = mtcars)

2. Options for plotting numeric second condition / by

Current behavior: if the second argument to condition / by is a numeric variable, it is converted into a factor when passed to aes(). Additionally, for plot_predictions(points = <not 0>) the points aren't colored.

This means that when building on such plots with the original numeric variable we get an error:

library(marginaleffects)
library(ggplot2)

mod <- lm(mpg ~ wt * hp, data = mtcars)

plot_predictions(mod, condition = c("wt", "hp")) +
  geom_point(aes(wt, mpg, color = hp), data = mtcars)
#> Error in `scale_colour_discrete()`:
#> ! Continuous value supplied to a discrete scale.
#> ℹ Example values: 110, 93, 175, 105, and 245.

Created on 2026-01-12 with reprex v2.1.1

I suggest two changes:

  1. Change default behavior to convert numeric second condition / by variable to an ordered factor.
  2. Allow user to ask for the variable to stay numeric.

3. autolayer() functions?

We can also go in the opposite direction - instead of adding ggplot elements to plot_*() outputs, we can add marginaleffects-derived layers to existing ggplots with some clever autolayer() methods?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions