Text wrap for plot titles

I have a long title for a plot in R and it keeps extending outside the plot window. How can I wrap the title over 2 rows?


Solution 1:

try adding "\n" (new line) in the middle of your title. For example:

plot(rnorm(100), main="this is my title \non two lines")

enter image description here

Solution 2:

You can use the strwrap function to split a long string into multiple strings, then use paste with collapse=\n to create the string to pass to the main title argument. You might also want to give yourself more room in the margin using the par function with the mar argument.

Solution 3:

By adding a line break:

plot(1:10, main=paste(rep("The quick brown fox", 3), sep="\n"))

This create a tile with three (identical) lines. Just use \n between your substrings.

Solution 4:

Include line break/newline (\n) in the title string, e.g.:

strn <- "This is a silly and overly long\ntitle that I want to use on my plot"
plot(1:10, main = strn)

Solution 5:

This might be useful for any sentence, so that it splits on words:

wrap_sentence <- function(string, width) {
  words <- unlist(strsplit(string, " "))
  fullsentence <- ""
  checklen <- ""
  for(i in 1:length(words)) {
    checklen <- paste(checklen, words[i])
    if(nchar(checklen)>(width+1)) {
      fullsentence <- paste0(fullsentence, "\n")
      checklen <- ""
    }
    fullsentence <- paste(fullsentence, words[i])
  }
  fullsentence <- sub("^\\s", "", fullsentence)
  fullsentence <- gsub("\n ", "\n", fullsentence)
  return(fullsentence)
}

I'm sure there's a more efficient way to do it, but it does the job.