Re: [R] Fitting large titles in a plot

From: Jim Price <>
Date: Thu, 6 Dec 2007 09:28:06 -0800 (PST)

I wrote a little utility function for exactly this reason, which I use with long titles. You may want to add calls to par to adjust the upper margin if you are using raw graphical functionality (plot et al) - but lattice adjusts the upper margin automatically so you wouldn't need to add anything else.

PrettyString <- function(theString, maxLength, collapse = "\n") {

 	words <- unlist(strsplit(theString, " "))
 	wordLengths <- unlist(lapply(strsplit(words, ""), length))

 	if(max(wordLengths) > maxLength) 
		stop("maxChar must be increased due to string length")

 	count = wordLengths[1]
 	results = vector()
 	currentLine = words[1]

 	for(i in 2:length(words))
  		if((count + wordLengths[i] + 1) > maxLength)
   			results = c(results, currentLine)
   			currentLine = words[i]
   			count = wordLengths[i]
   			currentLine = paste(currentLine, words[i])
   			count = count + wordLengths[i] + 1
		results <- c(results, currentLine)

 	paste(results, collapse = collapse)


Knowing the R list, someone can probably reduce this function to 2 lines of code.

Svempa wrote:
> I want to fit a fairly long main title for a plot, supposedly by changing
> row after a while. As for now it starts way outside the picture margin at
> the left and continues way out right passed the right margins.
>>plot(A,main="This is my really long title and it's so long that I can see just about half of it.")
> Any suggestions? Shouldn't be that hard.

View this message in context:
Sent from the R help mailing list archive at

______________________________________________ mailing list
PLEASE do read the posting guide
and provide commented, minimal, self-contained, reproducible code.
Received on Thu 06 Dec 2007 - 19:25:21 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Thu 06 Dec 2007 - 21:30:17 GMT.

Mailing list information is available at Please read the posting guide before posting to the list.