ggplot2:如何绘制正交回归线?

时间:2014-11-18 13:48:39

标签: r ggplot2 regression

我已经测试了两个不同的视觉感知测试的大量参与者样本 - 现在,我想看看两个测试的性能在多大程度上相关。

为了可视化相关性,我使用ggplot()在R中绘制散点图,我拟合回归线(使用stat_smooth())。但是,由于我的xy变量都是性能指标,因此我需要在拟合回归线时考虑这两个因素 - 因此,我不能使用简单的线性回归(使用{{1而且需要适合正交回归(或总最小二乘)。我该怎么做呢?

我知道我可以在stat_smooth(method="lm")中指定formula,但我不知道要使用哪种公式。据我所知,没有任何预设方法(stat_smooth())适用。

3 个答案:

答案 0 :(得分:4)

事实证明,您可以从(x,y)上的主成分分析中提取斜率和截距,如图here所示。这只是稍微简单一点,在基数R中运行,并且在Deming(...)中使用MethComp给出了相同的结果。

# same `x and `y` as @user20650's answer
df  <- data.frame(y, x)
pca <- prcomp(~x+y, df)
slp <- with(pca, rotation[2,1] / rotation[1,1])
int <- with(pca, center[2] - slp*center[1])

ggplot(df, aes(x,y)) + 
  geom_point() + 
  stat_smooth(method=lm, color="green", se=FALSE) +
  geom_abline(slope=slp, intercept=int, color="blue")

答案 1 :(得分:2)

警告:不熟悉这种方法

我认为您应该能够将slopeintercept传递给geom_abline以生成拟合线。或者,您可以定义自己的方法以传递给stat_smooth(如链接smooth.Pspline wrapper for stat_smooth (in ggplot2)所示)。我根据How to calculate Total least squares in R? (Orthogonal regression)建议使用了Deming包中的MethComp函数。

library(MethComp)
library(ggplot2)

# Sample data and model (from ?Deming example) 
set.seed(1)
M <- runif(100,0,5)
# Measurements:
x <-         M + rnorm(100)
y <- 2 + 3 * M + rnorm(100,sd=2)

# Deming regression
mod <- Deming(x,y)

# Define functions to pass to stat_smooth - see mnel's answer at link for details
# Defined the Deming model output as class Deming to define the predict method
# I only used the intercept and slope for predictions - is this correct?
f <- function(formula,data,SDR=2,...){
        M <- model.frame(formula, data)
        d <- Deming(x =M[,2],y =M[,1], sdr=SDR)[1:2]
        class(d) <- "Deming"
        d  
        }

# an s3 method for predictdf (called within stat_smooth)
predictdf.Deming <- function(model, xseq, se, level) {
                         pred <- model %*% t(cbind(1, xseq) )
                         data.frame(x = xseq, y = c(pred))
                         }

ggplot(data.frame(x,y), aes(x, y)) + geom_point() + 
          stat_smooth(method = f, se= FALSE, colour='red', formula=y~x, SDR=1) +  
          geom_abline(intercept=mod[1], slope=mod[2], colour='blue') +
          stat_smooth(method = "lm", se= FALSE, colour='green', formula = y~x)

enter image description here

因此将截距和斜率传递给geom_abline会产生相同的拟合线(如预期的那样)。所以如果这是正确的方法,那么就更容易理解这一点。

答案 2 :(得分:0)

MethComp软件包似乎已不再维护(已从CRAN中删除)。 Russel88/COEF允许将stat_ / geom_summarymethod="tls"一起使用以添加正交回归线。

基于此和wikipedia:Deming_regression,我创建了以下函数,这些函数允许使用1:以外的噪声比。


deming.fit <- function(x, y, noise_ratio = sd(y)/sd(x)) {
  if(missing(noise_ratio) || is.null(noise_ratio)) noise_ratio <- eval(formals(sys.function(0))$noise_ratio) # this is just a complicated way to write `sd(y)/sd(x)`
  delta <-  noise_ratio^2
  x_name <- deparse(substitute(x))

  s_yy <- var(y)
  s_xx <- var(x)
  s_xy <- cov(x, y)
  beta1 <- (s_yy - delta*s_xx + sqrt((s_yy - delta*s_xx)^2 + 4*delta*s_xy^2)) / (2*s_xy)
  beta0 <- mean(y) - beta1 * mean(x) 

  res <- c(beta0 = beta0, beta1 = beta1)
  names(res) <- c("(Intercept)", x_name)
  class(res) <- "Deming"
  res
}

deming <- function(formula, data, R = 100, noise_ratio = NULL, ...){
  ret <- boot::boot(
    data = model.frame(formula, data), 
    statistic = function(data, ind) {
      data <- data[ind, ]
      args <- rlang::parse_exprs(colnames(data))
      names(args) <- c("y", "x")
      rlang::eval_tidy(rlang::expr(deming.fit(!!!args, noise_ratio = noise_ratio)), data, env = rlang::current_env())
    },
    R=R
  )
  class(ret) <- c("Deming", class(ret))
  ret  
}

predictdf.Deming <- function(model, xseq, se, level) {
  pred <- as.vector(tcrossprod(model$t0, cbind(1, xseq)))
  if(se) {
    preds <- tcrossprod(model$t, cbind(1, xseq))
    data.frame(
      x = xseq,
      y = pred,
      ymin = apply(preds, 2, function(x) quantile(x, probs = (1-level)/2)),
      ymax = apply(preds, 2, function(x) quantile(x, probs = 1-((1-level)/2)))
    )
  } else {
    return(data.frame(x = xseq, y = pred))
  }
}

# unrelated hlper function to create a nicer plot:
fix_plot_limits <- function(p) p + coord_cartesian(xlim=ggplot_build(p)$layout$panel_params[[1]]$x.range, ylim=ggplot_build(p)$layout$panel_params[[1]]$y.range)

演示:

library(ggplot2)

#devtools::install_github("Russel88/COEF")
library(COEF)

fix_plot_limits(
    ggplot(data.frame(x = (1:5) + rnorm(100), y = (1:5) + rnorm(100)*2), mapping = aes(x=x, y=y)) +
      geom_point()
    ) +
  geom_smooth(method=deming, aes(color="deming"), method.args = list(noise_ratio=2)) +
  geom_smooth(method=lm, aes(color="lm")) +
  geom_smooth(method = COEF::tls, aes(color="tls"))

reprex package(v0.3.0)于2019-12-04创建