Skip to contents

Suppose we have a model with a complicated interaction between two continuous variables:

library(splines)
fit <- lm(
  Ozone ~ Solar.R + ns(Wind, df = 2) * ns(Temp, df = 2),
  data = airquality
)

We might wish to visualize how ozone depends on wind and temperature as a continuous regression surface. visreg2d provides two main options for this, raster plots and perspective plots.

Raster plots

The default is to provide a raster plot, built with ggplot2:

visreg2d(fit, "Wind", "Temp")

Here, wind and temperature are laid out on a two-dimensional grid, and colors are used to represent the level of ozone. A legend is provided to the right. Because the result is a ggplot2 object, you can further customize it as you would any other ggplot2 plot; for example, if we want different colors,

visreg2d(fit, "Wind", "Temp", color = c("black", "white", "purple"))

Perspective plots

The other option provided by visreg2d is to represent the surface as a three-dimensional image. This can be done in a static manner by computing the surface with plot = FALSE and passing the result to persp():

visreg2d(fit, "Wind", "Temp", plot = FALSE) |> persp()

Or dynamically using rgl::persp3d(). For this, you will need to install the rgl package first.

visreg2d(fit, "Wind", "Temp", plot = FALSE) |> rgl::persp3d()

You can interact with the above figure (click and drag to turn the surface about).