在基本的R中,反转绘制的GAM中的X和Y轴:

huangapple go评论72阅读模式
英文:

Reversing X and Y axes on plotted GAM in base R

问题

我想绘制一个GAM的输出,将X和Y轴颠倒,使得输出像这样:

在基本的R中,反转绘制的GAM中的X和Y轴:

变成像这样:

在基本的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:

在基本的R中,反转绘制的GAM中的X和Y轴:

is output like this:

在基本的R中,反转绘制的GAM中的X和Y轴:

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 &lt;- function(model) {
  dat &lt;- plot(model)[[1]]
  plot(c(dat$fit), dat$x, ylim = rev(dat$xlim), type = &quot;l&quot;, xaxt = &quot;n&quot;, 
       xlab = &quot;&quot;, 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 &lt;- mgcv::gam(mpg ~ s(wt), data = mtcars)  

The standard plot would be like this:

plot(mod)

在基本的R中,反转绘制的GAM中的X和Y轴:

But our flipped version would be:

plot_flipped(mod)

在基本的R中,反转绘制的GAM中的X和Y轴:

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>

huangapple
  • 本文由 发表于 2023年6月12日 02:03:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/76451846.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定