将x = y行添加到scatterplot

Cad*_*ama 11 plot r line scatter-plot

我正在使用汽车包中的scatterplot函数来生成散点图.我希望能够在图中生成一个应该是x = y的参考线.我尝试使用abline,它确实添加了一条线,但它不是x = y线.有人可以帮忙吗?

我的代码如下:

scatterplot(phenos$P1~pheno$P0, data=pheno,spread=FALSE,ylab="6 month timepoint", xlab="Baseline Timepoint", jitter=list(x=1, y=1))
abline(0,1)
Run Code Online (Sandbox Code Playgroud)

谢谢.

Ale*_*ese 5

您可以通过相同的功能实现目标abline。使用函数abline(a=0, b=1)where ab分别是线的截距和斜率。这将使您画出一条直线Y = a + b*x

希望这可以帮助。


Ben*_*ker 1

这实际上相当困难/hackish,因为scatterplot()内部使用layout,这使得很难控制图形驱动程序当前使用的子图。(更新:这比我想象的要难——设置par("mfg")肯定或多或少是偶然的。)

弥补数据(更新:使用均值x和y不等于0且彼此不相等的数据,因为它abline()更清楚地说明了天真的使用的困难)

set.seed(1)
d <- data.frame(x=rnorm(10,mean=10),y=rnorm(10,mean=12))
library(car)
Run Code Online (Sandbox Code Playgroud)

尝试我的旧策略(实际上不起作用,或者只是不可预测地起作用):

scatterplot(y~x,data=d,reset.par=FALSE)
k <- 1              
for (i in 1:2) {
   for (j in 1:2) {
      par(mfg=c(i,j,2,2))
        abline(0,1,lwd=3,col=k)
        k <- k+1
  }
Run Code Online (Sandbox Code Playgroud)

}

根据我执行此操作的方式,我要么收到警告和错误,要么收到虚假答案。scatterplot()我是否在函数内部进行调用似乎很重要......?

在此输入图像描述

第二次尝试,更保守:从头开始重建布局。

 scatterplot(y~x,data=d)
 uu <- par("usr")
 ## mimic layout frolm car:::scatterplot.default.  Would be different if we were drawing only one
 ## of x-boxes or y-boxes
 layout(matrix(c(1, 0, 3, 2), 2, 2), widths = c(5, 95), 
        heights = c(95, 5))
 oldmar <- par(mar=rep(0,4))  ## zero out margins so we can plot in sub-boxes without errors
 ## now skip through the first two sub-plots
 par(new=TRUE); plot.new(); par(new=TRUE); plot.new()
 par(oldmar)  ## reset margins
 ## blank plot with user limits set and 'interior' axis calculations
 plot(0:1,0:1,xlab="",ylab="",xlim=uu[1:2],ylim=uu[3:4],xaxs="i",yaxs="i")
 ## add annotation
 abline(a=0,b=1,col=4,lwd=3)              
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

考虑到该解决方案的工作量和脆弱性,实际上最好的办法是破解scatterplot以选择性地允许abline()另外指定,或者向维护人员询问该功能......