2

Long, multiline titles in ggplot2 that have \n line breaks in them stretch outside RStudio's window. To edit the title you have to scroll far to the right sometimes. It seems the title is all one string, indivisible.

How can such a long title be visible completely in the RStudio window (without resizing the window) to make it easier to edit? Ideally, I could insert a comma, then to start a new indented line for each of the additional title lines.

Here is a small example:

require(ggplot2)

DF <- data.frame(x = rnorm(400))
ggplot(DF, aes(x = x)) + geom_histogram() +
  ggtitle("First line very long title ending with newline\nSecond line also very long so it extends to the right out of RStudio pane\nThird line to emphasize how far you have to scroll right")

Is there a way to break up that long ggtitle() call?

It seemed this SO question could help, but I can't apply it's sprintf() solution to my problem. How to avoid linebreak in R's sprintf("very very long string with line break")?

Fmt <- c(" %s\n", "%s\n", "%s")
sprintf(paste(Fmt2, collapse = ""), "First line very long title ending with newline",
        "Second line also very long so it extends to the right out of RStudio pane",
        "Third line to emphasize how far you have to scroll right") 

Nor does this SO question help, since it is based on plotmath not cooperating with ggplot. R ggplot2 center align a multi-line title has to do with mixing plotmath and ggplot

Community
  • 1
  • 1
lawyeR
  • 7,488
  • 5
  • 33
  • 63

1 Answers1

1

Just use paste with sep = '\n'.

ggplot(DF, aes(x = x)) + geom_histogram() +
  ggtitle(paste("First line very long title ending with newline
          Second line also very long so it extends to the right out of RStudio pane
          Third line to emphasize how far you have to scroll right", sep='\n'))
shadow
  • 21,823
  • 4
  • 63
  • 77