gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 18:01:48 26 4
gpt4 key购买 nike

我正在对数据集进行相当复杂和长时间的统计分析,最终输出之一是带有居中标签的 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")



问题是:如何在矩形中自动拟合可变长度字符串,如下所示?
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")

最佳答案

联合 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

关于r - 如何在R中的矩形中包装文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45646204/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com