英文:
Reversing X and Y axes on plotted GAM in base R
问题
我想绘制一个GAM的输出,将X和Y轴颠倒,使得输出像这样:
变成像这样:
在基本的R中有没有一种好方法可以做到这一点?
在调用plot(GAM)时似乎进行了一些背景计算,所以我不能简单地颠倒输入的顺序。
英文:
I would like to plot the output from a GAM with the X and Y axes reversed, such that an output like this:
is output like this:
Is there a good way to do this in base R?
There seems to be some background calculations when plot(GAM) is called, so I can't just simply reverse the order of the input.
答案1
得分: 3
函数plot.gam
会隐式返回一个包含足够数据以重新创建绘图的列表,因此您可以使用以下函数自己构建翻转版本:
plot_flipped <- function(model) {
dat <- plot(model)[[1]]
plot(c(dat$fit), dat$x, ylim = rev(dat$xlim), type = "l", xaxt = "n",
xlab = "", ylab = dat$xlab)
axis(3)
suppressWarnings(rug(dat$raw, side = 2))
lines(dat$fit - dat$se, dat$x, lty = 2)
lines(dat$fit + dat$se, dat$x, lty = 2)
mtext(dat$ylab, side = 3, padj = -4)
}
所以,假设我们有这样一个模型:
mod <- mgcv::gam(mpg ~ s(wt), data = mtcars)
标准绘图将如下所示:
plot(mod)
但我们的翻转版本将是:
plot_flipped(mod)
有一些使用扩展包更简单的替代方法,您可以使用ggplot
获得更漂亮的版本,但这可能是仅使用基本R(而不将图像保存为位图并旋转它)完成的最简单方法。
<sup>在2023-06-11创建,使用 reprex v2.0.2</sup>
英文:
The function plot.gam
invisibly returns a list
containing enough data to recreate the plot, so you can build a flipped version yourself with this function:
plot_flipped <- function(model) {
dat <- plot(model)[[1]]
plot(c(dat$fit), dat$x, ylim = rev(dat$xlim), type = "l", xaxt = "n",
xlab = "", ylab = dat$xlab)
axis(3)
suppressWarnings(rug(dat$raw, side = 2))
lines(dat$fit - dat$se, dat$x, lty = 2)
lines(dat$fit + dat$se, dat$x, lty = 2)
mtext(dat$ylab, side = 3, padj = -4)
}
So, suppose we have a model like this:
mod <- mgcv::gam(mpg ~ s(wt), data = mtcars)
The standard plot would be like this:
plot(mod)
But our flipped version would be:
plot_flipped(mod)
There are alternative ways that would be easier using extension packages, and you could get a prettier version of the same thing using ggplot
, but this is probably the simplest way to do it using only base R (without saving the image as a bitmap and rotating it)
<sup>Created on 2023-06-11 with reprex v2.0.2</sup>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论