如何在R中的矩形中包装文本

JAS*_*ASC 5 text r rect

我正在对数据集执行相当复杂和长时间的统计分析,其中一个最终输出是具有居中标签的8个彩色正方形的组.颜色和标签都取决于分析结果,其中许多都是生产的,必须定期更新,因此不能手动编辑.正方形是2x2 cm2,在某些情况下,标签不适合正方形.如果我用cex减小字体大小,文本会变得太小.

这是一个简单的问题示例(我使用RStudio):

plot.new()
plot.window(xlim=c(0,5),ylim=c(0,5))
rect(1,1,4,4)
text(2,2,"This is a long text that should fit in the rectangle")
Run Code Online (Sandbox Code Playgroud)

问题是:如何在矩形中自动拟合变长字符串,如下图所示?

plot.new()
plot.window(xlim=c(0,5),ylim=c(0,5)) # Window covers whole plot space
rect(1,1,4,4)
text(2.5,3,"This is a long text")
text(2.5,2.5,"that should fit")
text(2.5,2,"in the rectangle")
Run Code Online (Sandbox Code Playgroud)

Kam*_*toń 5

组合strwidth以获得绘图上的实际宽度并strwrap包装文本.它并不完美(文本应该用像素宽度而不是字符数包裹),但在大多数情况下应该这样做.

plot.new()
plot.window(c(-1,1), c(-1,1))

rectangleWidth <- .6
s <- "This is a long text that should fit in the rectangle"

n <- nchar(s)
for(i in n:1) {
    wrappeds <- paste0(strwrap(s, i), collapse = "\n")
    if(strwidth(wrappeds) < rectangleWidth) break
}

textHeight <- strheight(wrappeds)       

text(0,0, wrappeds)
rect(-rectangleWidth/2, -textHeight/2, rectangleWidth/2, textHeight/2) # would look better with a margin added     
Run Code Online (Sandbox Code Playgroud)