How to wrap text in a rectangle in R

I perform a rather complicated and lengthy statistical analysis of a data set, and one of the final outputs is a group of 8 colored squares with a centered label. Both the color and the label depend on the results of the analysis, many of them are created, and they need to be updated periodically, so manual editing is not an option. Squares are 2x2 cm2, and in some cases the marks do not correspond to the square. If you reduce the font size with cex, the text will become too small.

This is a simple example of a problem (I am using 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 arises: how can I automatically insert a string of variable length into a rectangle, for example 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") 

+5
source share
2 answers

Combine strwidth to get the actual width on the graph and strwrap to wrap the text. This is not ideal (the text should be wrapped in pixel width, not the 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 
+5
source

Use the return return character in which you want to split. See the code below and interpret it.

 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. :)

+2
source

Source: https://habr.com/ru/post/1270808/


All Articles