4

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"))
}
Jaap
  • 81,064
  • 34
  • 182
  • 193
A. Huberts
  • 53
  • 1
  • 5
  • Welcome to StackOverflow! Please read the info about [how to ask a good question](http://stackoverflow.com/help/how-to-ask) and how to give a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/5963610). This will make it much easier for others to help you. – Jaap Nov 02 '15 at 18:40
  • @JasonAizkalns Please make that an answer. – Roland Nov 02 '15 at 18:53

1 Answers1

4

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).

JasonAizkalns
  • 20,243
  • 8
  • 57
  • 116
  • 2
    the strwrap was a neat solution. I ended up wanting much longer lines, but that was an easy fix in just changing the width parameter. Also played around with the line height using +theme(plot.title = element_text(size = 20, lineheight = 1, face = "bold")). Thanks for the help! – A. Huberts Nov 03 '15 at 15:44