Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wrap text in a rectangle in R

Tags:

text

r

rect

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

like image 731
JASC Avatar asked Aug 12 '17 03:08

JASC


2 Answers

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     
like image 142
Kamil Bartoń Avatar answered Oct 12 '22 21:10

Kamil Bartoń


Use return escape character where you want to separate. Please see the code below and interpret.

plot.new()
plot.window(xlim=c(0,5),ylim=c(0,5))
rect(0,0,4,4)
text(2,2,"This is a long text\nthat should fit\nin the rectangle")

Hope this helps you. :)

like image 43
Akarsh Jain Avatar answered Oct 12 '22 22:10

Akarsh Jain