使用表达式等创建多行标签

时间:2012-08-15 13:07:17

标签: r

以下是代码

的示例
set.seed(1)
tmp <- matrix(replicate(4, rnorm(50)), ncol=4)
panel.cor <- function(x, y, digits=2, prefix="", cex.cor, ...)
{
  usr <- par("usr"); on.exit(par(usr))
  par(usr = c(0, 1, 0, 1))
  rp <- cor(x, y, method="pearson", use="pairwise.complete.obs")
  rs <- cor(x, y, method="spearman", use="pairwise.complete.obs")
  rp <- format(rp, digits=digits)
  rs <- format(rs, digits=digits)
  txt <- substitute(list(R[p] == rp, R[s] == rs), list(rp=rp, rs=rs))
  if(missing(cex.cor)) cex.cor <- 0.8/strwidth(txt)
  text(0.5, 0.5, txt, cex = 1.5)
}
panel.my.points <- function(x, y) {
  points(x, y)
  abline(0, 1)
}
pairs(tmp, 
      lower.panel=panel.cor, 
      upper.panel=panel.my.points, 
      labels=c("model 1\nD1", "model 2\nD1", "model 1\nD2", "model 2\nD2"))

返回图表 enter image description here 但我想在不同的线上显示两个相关系数Pearson和Spearman。对于普通文本,我插入\n来生成两行输出(如对角线上的标签)。我该怎么做才能在两行中输出相关系数?

1 个答案:

答案 0 :(得分:2)

如何分别定义Pearson(下面的代码中为txta)和Spearman(txtb)系数,然后再调用text两次:

set.seed(1)
tmp <- matrix(replicate(4, rnorm(50)), ncol=4)
panel.cor <- function(x, y, digits=2, prefix="", cex.cor, ...)
{
  usr <- par("usr"); on.exit(par(usr))
  par(usr = c(0, 1, 0, 1))
  rp <- cor(x, y, method="pearson", use="pairwise.complete.obs")
  rs <- cor(x, y, method="spearman", use="pairwise.complete.obs")
  rp <- format(rp, digits=digits)
  rs <- format(rs, digits=digits)
  txt <- substitute(list(R[p] == rp, R[s] == rs), list(rp=rp, rs=rs))
  txta <- substitute(R[p] == rp, list(rp=rp))
  txtb <- substitute(R[s] == rs, list(rs=rs))
  if(missing(cex.cor)) cex.cor <- 0.8/strwidth(txt)
  text(0.5, 0.6, txta, cex = 1.5)
  text(0.5, 0.4, txtb, cex = 1.5)
}
panel.my.points <- function(x, y) {
  points(x, y)
  abline(0, 1)
}
pairs(tmp, 
      lower.panel=panel.cor, 
      upper.panel=panel.my.points, 
      labels=c("model 1\nD1", "model 2\nD1", "model 1\nD2", "model 2\nD2"))

这给出了:

enter image description here