如何在R语言中反转广义加性模型3D透视图的Z轴?
如何反转GAM模型3D透视图的Z轴方向
问题描述
我绘制了广义加性模型(generalized additive models)的3D透视图,但Z轴Growers (proportion)的数值默认是从上到下读取的,希望反转Z轴,改为从下到上显示数值。
可复现代码:
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
解决方案
要反转vis.gam生成的3D透视图Z轴,核心是通过反转Z轴的数值范围实现方向调整,以下是两种可行方法:
方法1:自动获取并反转Z轴范围
先计算模型预测值的范围,再通过rev()反转后传入zlim参数,确保轴范围准确匹配数据:
# 计算x1-x2维度的Z值范围并反转 z_range1 <- range(predict(mod, newdata = expand.grid(x1=seq(0,1,length=100), x2=seq(0,1,length=100)))) p1 <- wrap_elements(panel = ~vis.gam(mod, view = c("x1", "x2"), zlab = "Growers (proportion)", theta = 120, plot.type = "persp", type = "response", ticktype = "detailed", zlim = rev(z_range1))) # 计算x3-x4维度的Z值范围并反转 z_range2 <- range(predict(mod, newdata = expand.grid(x3=seq(0,1,length=100), x4=seq(0,1,length=100)))) p2 <- wrap_elements(panel = ~vis.gam(mod, view = c("x3", "x4"), zlab = "Growers (proportion)", theta = 35, plot.type = "persp", type = "response", ticktype = "detailed", zlim = rev(z_range2))) fig <- p1 + p2 + plot_layout(ncol = 2, tag_level = 'new') + plot_annotation(tag_levels = list(c('(a)', '(b)'))) fig
方法2:手动指定反转后的Z轴范围
如果已知Z值的大致区间(比如0到1),可以直接手动传入反转后的范围:
p1 <- wrap_elements(panel = ~vis.gam(mod, view = c("x1", "x2"), zlab = "Growers (proportion)", theta = 120, plot.type = "persp", type = "response", ticktype = "detailed", zlim = c(1, 0))) # 手动指定反转范围 p2 <- wrap_elements(panel = ~vis.gam(mod, view = c("x3", "x4"), zlab = "Growers (proportion)", theta = 35, plot.type = "persp", type = "response", ticktype = "detailed", zlim = c(1, 0))) fig <- p1 + p2 + plot_layout(ncol = 2, tag_level = 'new') + plot_annotation(tag_levels = list(c('(a)', '(b)'))) fig
原理说明
vis.gam的plot.type="persp"本质调用基础绘图的persp函数,该函数通过zlim参数控制Z轴范围。当范围的最大值在前、最小值在后时,轴的显示方向会自动反转,从而实现数值从下到上递增的效果。
内容的提问来源于stack exchange,提问作者Ahsk
相关产品推荐
相关产品推荐

