A. Huberts
A. Huberts

Reputation: 63

In ggplot2, can I split my titles into multiple lines automatically, instead of using the escape \n?

I've written a function to make graphs for a large dataset with hundreds of questions. All of the graphs are from the same dataset, and pull the title as a string from the 'graphtitle' column of a csv i've read in. Some of these titles are rather long and should be split to two lines. Perhaps because they're coming from the csv, the titles don't function with an \n escape, and even if they did, it seems like there should be an easier way than adding \n to each variable name in the appropriate place in the CSV.

Is there a way to make my function split the title lines automatically? I know I could change the size of the title, but that will render it largely illegible

MC.Graph <- function(variable){
    p <- ggplot(data = newBEPS, aes_string(x=variable)) + geom_bar(aes(y = (..count..)/sum(..count..)), width = .5)+ scale_y_continuous(labels = percent)
    p <- p + ggtitle(graphwords$graphtitle[graphwords$gw.varname == variable]) + 
    theme(plot.title = element_text(size =20, lineheight = .5, face = "bold"))
}

Upvotes: 5

Views: 4130

Answers (1)

JasonAizkalns
JasonAizkalns

Reputation: 20483

Here are two ways to break up a long string:

  1. gsub('(.{1,10})(\\s|$)', '\\1\n', s) will break up string, s, into lines of length 10 separated by \n.
  2. Use the strwrap function with a width argument wrapped with a paste function and collapse = \n argument.

Easier to understand with examples...

long_title <- "This is a title that is perhaps too long to display nicely"

gsub('(.{1,10})(\\s|$)', '\\1\n', long_title)
# [1] "This is a\ntitle that\nis perhaps\ntoo long\nto display\nnicely\n"

paste(strwrap(long_title, width = 10), collapse = "\n")
# [1] "This is a\ntitle\nthat is\nperhaps\ntoo long\nto\ndisplay\nnicely"

N.B. I believe strwrap is handled more gracefully (and guessing efficiently) in the stringi and/or stringr packages (see stringi::stri_wrap or stringr::str_wrap).

Upvotes: 5

Related Questions