2015-04-07 34 views
1

假设我正在做一个y ~ x的线性模型。我得到的残差图与例如在R的plot.lm中设置ylim残差plot

plot(lm(y ~ x, data.frame(x=c(1,2,3), y=c(4,6,9))), 1) 

如何设置此阴谋的ylim? (例如,为此函数提供ylim = c(-1,1)不起作用)。

回答

1

ylim被硬编码到函数stats:::plot.lm中(即,用于类“lm”的对象的s3 plot方法)。该功能不会从统计数据包中导出。为了解决这个问题,你可以复制的功能,并修改它:

plotlm <- stats:::plot.lm 

可以使用fix("plotlm")编辑。向函数定义添加一个ylim形式参数,然后找到代码的相关部分。你应该改变:

if (show[1L]) { 
    ylim <- range(r, na.rm = TRUE) 
    if (id.n > 0) 
     ylim <- extendrange(r = ylim, f = 0.08) 
    dev.hold() 
    plot(yh, r, xlab = l.fit, ylab = "Residuals", main = main, 
     ylim = ylim, type = "n", ...) 
# ... 

到:

if (show[1L]) { 
    if(missing(ylim)) { 
     ylim <- range(r, na.rm = TRUE) 
     if (id.n > 0) 
      ylim <- extendrange(r = ylim, f = 0.08) 
    } 
    dev.hold() 
    plot(yh, r, xlab = l.fit, ylab = "Residuals", main = main, 
     ylim = ylim, type = "n", ...) 
# ... 

然后你就可以把这种新的功能:

plotlm(lm(y ~ x, data.frame(x=c(1,2,3), y=c(4,6,9))), 1, ylim = c(-1,1)) 

得到期望的结果:

enter image description here