How to break caption text in R

Asked

Viewed 226 times

-2

I need to plot a legend that has a very large text. But the problem is that when I export the R figure, part of the text is outside the Plot area. I wonder if there is a way I break the text of the legend in two parts, so that it fits in the area of Plot.

What do I have:

texto1 <- "Esse texto é muito grande e portanto precisa ser quebrado em duas partes"
texto2 <- "Esse texto também é muito grande e precisa ser quebrado em duas partes"

plot(NULL, xaxt="n", yaxt="n", bty="n", ylab="", xlab="", xlim=0:1, ylim=0:1)
    
legend("center", legend = c(texto1,texto2), pch=15, pt.cex=3, cex=1.1, bty="n",
       col = c("red", "blue"), y.intersp =1.5)
  • 6

    You tried to use a line break \n?

  • 1

    @Lucas had never used this line break. But she does exactly what I need. Thank you!

1 answer

1

Here’s a simple function to break the line into as many pieces as you want (two by default):

div.texto <- function(string, n = 2) {
  comp <- (nchar(string)/n)*1.2
  paste(strwrap(string, comp), collapse = "\n")
}

nchar gives the number of characters in a string. crash breaks a text into pieces of the maximum specified size (hence the *1.2; the size of each block will vary according to the size of the words, there is no guarantee of the exact number of divisions). The code \n indicates line break.

plot(NULL, xaxt="n", yaxt="n", bty="n", ylab="", xlab="", xlim=0:1, ylim=0:1)
legend("center", 
       legend = c(div.texto(texto1), div.texto(texto2, 3)),
       pch=15, pt.cex=3, cex=1.1, bty="n", col = c("red", "blue"), y.intersp =1.5)

inserir a descrição da imagem aqui

Browser other questions tagged

You are not signed in. Login or sign up in order to post.