Text wrap for plot titles
I have a long title for a plot in R and it keeps extending outside the p开发者_如何转开发lot window. How can I wrap the title over 2 rows?
try adding "\n" (new line) in the middle of your title. For example:
plot(rnorm(100), main="this is my title \non two lines")
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.
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.
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)
You can use strwrap
and paste
to automatically wrap the title of your graph. The width need to be adapted to your media width.
plot(rnorm(100), main = paste(
strwrap(
'This is a very long title wrapped on multiple lines without the need to adjust it by hand',
whitespace_only = TRUE,
width = 50
),
collapse = "\n"
))
R should do that automatically, nobody want cropped title.
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.
A little on the late side but I found this while I was trying to figure out how to remove the line breaks from my histogram title. Anyway, I think this seems like the easiest option to me. No extra space from \n either. If you want it without line breaks then use paste() instead of c().
plot(rnorm(100), main=c("this is my title","on two lines")) Example plot for evidence
In case you want to go with one of the "\n" solutions, keep in mind it's also possible for the title to get too tall and spill over the top. If your generating lines dynamically, you can keep track of the line count and solve the problem like this:
mar = par()$mar #get the current margins
mar[3] = mar[3] + line_count #increase the top margin if the title has too many lines
par(mar = mar) #set the new margins
hist(rnorm(100), main = title)
You can just wrap whatever text you want to plot in str_wrap and specify the characters in width argument. So you can use this in title, subtitle, caption etc.
library(stringr)
str_wrap(x, width = 15)
精彩评论