如何在R

时间:2015-07-12 18:45:05

标签: r text plot labels rectangles

我希望每个矩形包含一个数字,以便第一个绘制的矩形包含:rect 1,第二个rect 2,依此类推,但我不知道如何在矩形内插入文本。

require(grDevices)
## set up the plot region:

plot(c(0, 250), c(0, 250), type = "n",
     main = "Exercise 1: R-Tree Index Question C")

rect(0.0,0.0,40.0,35.0, , text= "transparent")
rect(10.0,210.0,45.0,230.0)
rect(170.0,50.0,240.0,150.0)
rect(75.0,110.0,125.0,125.0)
rect(50.0,130.0,65.0,160.0)
rect(15.0,140.0,30.0,150.0)
rect(100.0,50.0,130.0,90.0)
rect(150.0,40.0,155.0,60.0)
rect(52.0,80.0,75.0,90.0)
rect(62.0,65.0,85.0,75.0)
rect(20.0,75.0,25.0,80.0)
rect(30.0,40.0,50.0,80.0)
rect(102.0,155.0,113.0,217.0)



par(op)

3 个答案:

答案 0 :(得分:2)

与其他答案一样,您可以使用您提供给rect的坐标将文本放在相对的位置。

plot(c(0, 250), c(0, 250), type = "n",
     main = "Exercise 1: R-Tree Index Question C")
rect(0.0,0.0,40.0,35.0)
center <- c(mean(c(0, 40)), mean(c(0, 35)))
text(center[1], center[2], labels = 'hi')

您可以轻松地将其置于一个函数中以节省一些输入/错误

recttext <- function(xl, yb, xr, yt, text, rectArgs = NULL, textArgs = NULL) {
  center <- c(mean(c(xl, xr)), mean(c(yb, yt)))
  do.call('rect', c(list(xleft = xl, ybottom = yb, xright = xr, ytop = yt), rectArgs))
  do.call('text', c(list(x = center[1], y = center[2], labels = text), textArgs))
}

像这样使用

recttext(50, 0, 100, 35, 'hello',
         rectArgs = list(col = 'red', lty = 'dashed'),
         textArgs = list(col = 'blue', cex = 1.5))

enter image description here

答案 1 :(得分:1)

text( (0.0+40.0)/2, (0.0+35.0)/2 , 'transparent')

我们选择x,y作为矩形的质心。您可以定义一个函数来绘制rect,然后将text放在其质心处。

注意:这些坐标很大;这将显示在您的正常视图之外。所以你需要放大才能看到它,或者将坐标缩放到范围0.0..1.0

顺便说一下,请阅读12.2 Low-level plotting commands

答案 2 :(得分:1)

您需要将text()用作单独的图形调用。

coords <- matrix(
c(0.0,0.0,40.0,35.0,
    10.0,210.0,45.0,230.0,
    170.0,50.0,240.0,150.0,
    75.0,110.0,125.0,125.0,
    50.0,130.0,65.0,160.0,
    15.0,140.0,30.0,150.0,
    100.0,50.0,130.0,90.0,
    150.0,40.0,155.0,60.0,
    52.0,80.0,75.0,90.0,
    62.0,65.0,85.0,75.0,
    20.0,75.0,25.0,80.0,
    30.0,40.0,50.0,80.0,
    102.0,155.0,113.0,217.0),
ncol=4,byrow=TRUE)

 plot(c(0, 250), c(0, 250), type = "n",
         main = "Exercise 1: R-Tree Index Question C")
rfun <- function(x,i) {
    do.call(rect,as.list(x))
}
apply(coords,1,rfun)
text((coords[,1]+coords[,3])/2,
     (coords[,2]+coords[,4])/2,
     seq(nrow(coords)))