我正在对数据集进行相当复杂且长时间的统计分析,最终输出之一是带有中心标签的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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句