I am performing a rather complex and long statistical analysis of a dataset and one of the final outputs are groups of 8 colored squares with a centered label. Both color and label depend on the analysis results, many of them are produced and they must be updated periodically, so manual editing is not an option. The squares are 2x2 cm2 and in some cases the labels do not fit the square. If I reduce the font size with cex the text becomes too small.
This is a simple example of the problem (I use 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")
The question is: how can I automatically fit a variable length string in a rectangle, such as below?
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")
Combine strwidth
to get the actual width on the plot and strwrap
to wrap the text. It isn't perfect (the text should be wrapped by pixel width and not number of characters), but should do in most cases.
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