如何在R中的条形图错误栏功能中添加标签

时间:2013-05-27 12:00:46

标签: r labels boxplot

我已经获得了以下功能来创建一个带错误条的盒子图,效果很好。

但是我需要添加轴标签,我已经有两天时间试图找出这样添加代码的位置

# col=c(2,7),ylab="Relative Fitness",xlab="Block")

error.bars<-function(Response,x1,x2)  {
   mean.table<-tapply(Response,list(x1,x2),mean)
   mean.table[is.na(mean.table)]<-0
   var.table<-tapply(Response,list(x1,x2),var)
   n.table<-tapply(Response,list(x1,x2),length)
   std.errors<-sqrt(var.table/n.table)
   std.errors[is.na(std.errors)]<-0
   biggest.value<-max(mean.table+std.errors)

   bartable<-barplot(mean.table,beside=TRUE,
   ylim=c(0,biggest.value+1))

   errbar.width<-(max(bartable)-min(bartable))/50

   for(i in 1:length(mean.table[,1])) {

      for(j in 1:length(mean.table[1,])) {

          lines(c(bartable[i,j],bartable[i,j]),
          c(mean.table[i,j]-std.errors[i,j],
          mean.table[i,j]+std.errors[i,j]))

          lines(c(bartable[i,j]-errbar.width,
          bartable[i,j]+errbar.width),
          c(mean.table[i,j]+std.errors[i,j],
          mean.table[i,j]+std.errors[i,j]))

          lines(c(bartable[i,j]-errbar.width,
          bartable[i,j]+errbar.width),
          c(mean.table[i,j]-std.errors[i,j],
    mean.table[i,j]-std.errors[i,j]))

     }
  }
}

任何提示非常感谢


因为我不清楚而道歉,我是R的新手,这个网站如此不确定如何传达信息。我的数据很简单,看起来像这样。 n = 3个块,n = 33行,n = 2表示性别,我的y变量是Fitness。我已经能够使用我之前发布的errorbars函数的函数制作一个boxplot。但是我想要做的就是在函数中添加x和y轴标签。看似简单,但我无法弄清楚。

头(OzGLM)   Block Line性别健身 1 1 3 1 0.6865626 2 1 3 2 0.4874816 3 1 4 1 0.4219811 4 1 4 2 0.3829161 5 1 5 1 0.6071388 6 1 5 2 0.4432990

2 个答案:

答案 0 :(得分:1)

您可以使用mtext添加轴标签。

例如,将此添加到您的函数中:

    }
  }
  mtext('axisY',2)
  mtext('axisx',3)   ## since your barplot can hide the text I put the x axis label in the top
}

答案 1 :(得分:0)

这就是我这样做的方式,假设我知道你想要什么。我建立在agstudy的伟大建议之上。我把你的功能变成了这个:

  error.bars<-function(Response,x1,x2,label.x,label.y)

然后我将其添加到代码底部的agstudy代码中:

 }   
 mtext(label.y,2)  
 mtext(label.x,3)  
}  

最后发出命令:

  error.bars(data1,data2,data3,"x-axis","y-axis")  

此时我的标签标有“x轴”和“y轴”。但是,我不清楚应该在Response,x1和x2中放置什么,所以我得到了一个主要是垃圾的图,除了轴标签。 :)