Skip to contents

Add 3d marginal effects to a plot_ly plot

Usage

add_marginals(
  p,
  model,
  data = NULL,
  ci = TRUE,
  x1_constant_val = "mean",
  x2_constant_val = "mean",
  x1_color = "darkorange",
  x2_color = "crimson",
  x1_direction_name = "Predicted marginal effect of x1",
  x2_direction_name = "Predicted marginal effect of x2",
  omit_x1 = FALSE,
  omit_x2 = FALSE
)

Arguments

p

A plotly object

model

A lm or glm with exactly two x variables

data

An optional dataframe to be used to create the regression surface. By default, this will be the data used by the inherited plotly object.

ci

A logical. Defaults to TRUE, showing the confidence intervals of the predicted effects.

x1_constant_val, x2_constant_val

A string or numeric value indicating which constant value to set for x1 or x2 when the marginal effect of x2 is plotted. Defaults to the mean value. The string can take on "mean", "median", "min", or "max". Alternately, a numeric value may be specified.

x1_color

The color to be used for the line(s) depicting the marginal effect of x1. Defaults to "darkorange".

x2_color

The color to be used for the line(s) depicting the marginal effect of x2. Defaults to "crimson".

x1_direction_name

The hover text for the plotted line(s). Defaults to "Predicted marginal effect of x1".

x2_direction_name

The hover text for the plotted line(s). Defaults to "Predicted marginal effect of x2".

omit_x1, omit_x2

An optional logical. Defaults to FALSE. If set to TRUE, the marginal effect for that variable will not be included.

Value

A plotly object with the predicted marginal effects added to the plot.

Details

Additional plotly layers such as add_markers() can be added to the plotly plot, but be aware that many plotly layers inherit the data from the prior layer. As such, a function such as add_markers() may not work as intended if called after add_marginals().

Examples

library(plotly)
mymodel <- lm(r_shift ~ median_income16 + any_college,
              data = cali_counties, weight = pop_estimate16)
p <- plot_ly( data = cali_counties,
         x = ~median_income16,
         y = ~any_college,
         z = ~r_shift) %>%
  add_marginals(model = mymodel)