pairs()将标签移动到散点图的两侧

时间:2012-11-13 19:19:15

标签: r

对于虹膜数据,我们使用pairs()函数得到散点图,如下所示:

pairs(iris[1:4], 
      main = "Edgar Anderson's Iris Data", 
      lower.panel=panel.pearson, 
      pch = 21, 
      bg = c("red", "green3", "blue")[unclass(iris$Species)])

功能panel.pearson定义如下:

panel.pearson <- function(x, y, ...) { horizontal <- (par("usr")[1] + par("usr")[2]) / 2; vertical <- (par("usr")[3] + par("usr")[4]) / 2; text(horizontal, vertical, format(abs(cor(x,y)), digits=2)) }

我需要将下面板转换为相关矩阵,并从对角线上移除标签并将它们沿右轴和下轴放置。我尝试了以下方法:

pairs(iris[1:4], 
      main = "Edgar Anderson's Iris Data", 
      labels=NULL, 
      lower.panel=panel.pearson, 
      xaxt='n', 
      yaxt='n', 
      pch = 21, 
      bg = c("red", "green3", "blue")[unclass(iris$Species)])

这给了我我需要的东西。除了我不明白如何获得底部和右侧轴上的标签(变量标签,我的意思是,Sepal.Length,Sepal.Width等...)。非常感谢任何帮助。谢谢!

1 个答案:

答案 0 :(得分:0)

这是你的想法吗?

# Horizontal axis
text(seq(.2, 2, length.out=4), 0,
     c("Sepal Length","Sepal Width","Petal Length","Petal Width"),
     xpd=TRUE, adj=c(0,.5), cex=.9)

# Vertical axis
text(0, seq(0.35, 2.05, length.out=4),
     rev(c("Sepal Length","Sepal Width","Petal Length","Petal Width")),
     xpd=TRUE, adj=c(0.5, 0), 
     srt=90,  # rotates text to be parallel to axis
     cex=.9)

我通过反复试验来定位标签。可能有更好的方法,但至少这会使标签(几乎)在正确的位置。

更新new SO question给了我一个更好的方法来定位轴标签的想法。如链接的答案所指出的,您可以使用par('usr')获取绘图区域的当前坐标。所以这是对代码的更新,基于:

x.coords = par('usr')[1:2]
y.coords = par('usr')[3:4]

# Offset is estimated distance between edge of plot area and beginning of actual plot
x.offset = 0.03 * (x.coords[2] - x.coords[1])  
xrng =  (x.coords[2] - x.coords[1]) - 2*x.offset
x.width = xrng/4  

y.offset = 0.028 * (y.coords[2] - y.coords[1])
yrng =  (y.coords[2] - y.coords[1]) - 2*y.offset
y.width = yrng/4  

# seq function below calculates the location of the midpoint of each panel

# x-axis labels
text(seq(x.coords[1] + x.offset + 0.5*x.width, x.coords[2] - x.offset - 0.5*x.width,
         length.out=4), 0,
     c("Sepal Length","Sepal Width","Petal Length","Petal Width"),
     xpd=TRUE,adj=c(.5,.5), cex=.9)

# y-axis labels
text(0, seq(y.coords[1] + y.offset + 0.5*y.width, y.coords[2] - 3*y.offset - 0.5*y.width, 
     length.out=4),
     rev(c("Sepal Length","Sepal Width","Petal Length","Petal Width")),
     xpd=TRUE, adj=c(0.5, 0.5), 
     srt=90,  # rotates text to be parallel to axis
     cex=.9)

它仍然不理想,因为偏移的大小是由反复试验决定的。如果有人知道R如何确定绘图区域边界与实际绘图开始位置之间的偏移大小,则也可以通过编程方式确定偏移量。