How to invert z axis in a 3D plot in R?

84 views Asked by At

I have plotted a 3D perspective plot for generalized additive models. However, the Z-axis Growers (proportion) read from top to bottom. I see that is the default setting, but I'm interested in inverting the Z-axis to display values from bottom to top instead

Reproducible example:

n <- 200
sig2 <- 4
x1 <- runif(n, 0, 1)
x2 <- runif(n, 0, 1)
x3 <- runif(n, 0, 1)
x4 <- runif(n, 0, 1)
y <- x1^2 + x1 * x2 * x4

mod <- gam(y ~ s(x1, x2) + s(x3, x4))


p1 <- wrap_elements(panel = ~vis.gam(mod, view = c("x1",  "x2"), zlab = "Growers (proportion)", 
                                     theta = 120, plot.type = "persp", type = "response", ticktype = "detailed"))
p2 <- wrap_elements(panel = ~vis.gam(mod, view = c("x3",  "x4"), zlab = "Growers (proportion)", 
                                     theta = 35, plot.type = "persp", type = "response", ticktype = "detailed"))

fig <- p1 + p2 + plot_layout(ncol = 2, tag_level = 'new') +
  plot_annotation(tag_levels = list(c('(a)', '(b)'))) 
fig

Here is the current plot. As you can see, the Z-axis Growers (proportion) reads from top to bottom. Can we somehow invert the Z-axis?

enter image description here

1

There are 1 answers

0
user2554330 On

I believe the rule for both vis.gam() (which uses persp()) and plot_ly() is that the text will appear parallel to the axis, with the direction chosen so that the top of the text appears above the text in the plot.

With the orientation you chose for the plots, the z-axis tilts to the left when moving upwards, so the top of the text will be chosen to be towards the axis. If you change the orientation of the display by enough to have the axis tilt to the right, the text will switch orientations. For example:

library(mgcv)
#> Loading required package: nlme
#> This is mgcv 1.9-0. For overview type 'help("mgcv-package")'.
n <- 200
sig2 <- 4
x1 <- runif(n, 0, 1)
x2 <- runif(n, 0, 1)
x3 <- runif(n, 0, 1)
x4 <- runif(n, 0, 1)
y <- x1^2 + x1 * x2 * x4

mod <- gam(y ~ s(x1, x2) + s(x3, x4))

vis.gam(mod, view = c("x1",  "x2"), zlab = "Growers (proportion)", 
                                     theta = 120, phi = -15, plot.type = "persp", type = "response", ticktype = "detailed")

Created on 2023-12-19 with reprex v2.0.2

I don't think the orientation I've chosen is particularly good. If you want to find a good one using persp(), you'll have a lot of trial and error.

plot_ly() may have an option to flip the text; I'm pretty sure persp() doesn't.