【问题标题】:How to draw regression line instead of lowess line in `pairs()` in R? [duplicate]如何在 R 的“pairs()”中绘制回归线而不是低线? [复制]
【发布时间】:2018-03-14 23:33:58
【问题描述】:

我正在尝试用回归线绘制函数而不是低线替换 pairs() 中的参数 panelpanel.smooth,但没有成功。

我尝试创建函数 reg 并将其放置在参数 panel 中,但这不起作用?有什么办法吗?

reg <- function(x, y) abline(lm(y~x)) # made to draw regression line instead of lowess line


panel.cor <- function(x, y, digits = 2, prefix = "", cex.cor, ...)
{
 usr <- par("usr"); on.exit(par(usr))
 par(usr = c(0, 1, 0, 1))
 r <- abs(cor(x, y))
 txt <- format(c(r, 0.123456789), digits = digits)[1]
 txt <- paste0(prefix, txt)
 text(0.5, 0.5, txt, cex = 1.1, font = 4)
 }
 #EXAMPLE OF USE:
pairs(USJudgeRatings[1:5], panel = panel.smooth, # replace HERE for panel.smooth #
  cex = 1.5, pch = 19, col = adjustcolor(4, .4), cex.labels = 2, font.labels = 2, lower.panel = panel.cor)

【问题讨论】:

    标签: r plot


    【解决方案1】:

    你从未使用过你的函数reg。我稍微修改了reg 以采用颜色参数。我没有使用panel.smooth(给出黄土曲线),而是将其修改为使用线性模型和您的 reg 函数。

    reg <- function(x, y, col) abline(lm(y~x), col=col) 
    
    panel.lm =  function (x, y, col = par("col"), bg = NA, pch = par("pch"), 
        cex = 1, col.smooth = "red", span = 2/3, iter = 3, ...)  {
        points(x, y, pch = pch, col = col, bg = bg, cex = cex)
        ok <- is.finite(x) & is.finite(y)
        if (any(ok)) reg(x[ok], y[ok], col.smooth)
    }
    
    pairs(USJudgeRatings[1:5], panel = panel.lm,
        cex = 1.5, pch = 19, col = adjustcolor(4, .4), cex.labels = 2, 
        font.labels = 2, lower.panel = panel.cor)
    

    【讨论】:

      【解决方案2】:

      您需要在reg 中定义散点图以及lm 拟合线。

      reg <- function(x, y, ...) {
        points(x,y, ...)
        abline(lm(y~x)) 
        }# made to draw regression line instead of lowess line
      
      panel.cor <- function(x, y, digits = 2, prefix = "", cex.cor, ...)
      {
        usr <- par("usr"); on.exit(par(usr))
        par(usr = c(0, 1, 0, 1))
        r <- abs(cor(x, y))
        txt <- format(c(r, 0.123456789), digits = digits)[1]
        txt <- paste0(prefix, txt)
        text(0.5, 0.5, txt, cex = 1.1, font = 4)
      }
      #EXAMPLE OF USE:
      pairs(USJudgeRatings[1:5], upper.panel = reg, # replace HERE for panel.smooth #
            cex = 1.5, pch = 19, col = adjustcolor(4, .4), cex.labels = 2, font.labels = 2, lower.panel = panel.cor)
      

      【讨论】:

        猜你喜欢
        • 2017-02-05
        • 2020-12-25
        • 2016-07-09
        • 2015-03-19
        • 1970-01-01
        • 1970-01-01
        • 2016-05-12
        • 2019-12-06
        • 2016-08-09
        相关资源
        最近更新 更多