如何在R中的矩形内写入文本

how to write text inside a rectangle in R

我希望每个矩形包含一个数字,这样第一个绘制的矩形将包含: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)
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

您需要使用 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)))

就像提到的其他答案一样,您可以使用给 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')

您可以轻松地将其放入函数中以节省一些 typing/errors

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))