rggplot2line-breaksggtitle

Automatic line break in ggtitle


Is there a way to force an automatic line break in the ggtitle command?

As part of a shiny application I use different plots with an input variable for the title. Unfortunately, some of these variable values are too long to be displayed.

I came across one possibility by inserting \n (or a line break) manually in advance (Details here: Improve editing of multiline title in ggplot that uses \n and extends far to the right). There, something like ggtitle(paste("", title, "", sep = "\n")) would be suggested.

Since including \n would be error prone as well as not flexible for different plot sizes I´m looking for another possibility.

Here is an minimal working example (adapted from lawyeR question linked above):

DF <- data.frame(x = rnorm(400))
title_example <- "This is a very long title describing the plot in its details. The title should be fitted to a graph, which is itself not restricted by its size."
plot <- ggplot(DF, aes(x = x)) + geom_histogram() +
  ggtitle(title_example)

You can find a image here: https://i.sstatic.net/6MMKF.jpg

Do you have an idea how to e.g. adapt the sep = operator to break lines automatically or are there maybe packages/ workarounds? Thanks!


Solution

  • The ggtext package's text elements could help solve this. element_textbox_simple() automatically wraps the text inside. Try resizing the graphics device window, it adapts!

    library(ggplot2)
    library(ggtext)
    
    DF <- data.frame(x = rnorm(400))
    title_example <- "This is a very long title describing the plot in its details. The title should be fitted to a graph, which is itself not restricted by its size."
    
    ggplot(DF, aes(x = x)) + geom_histogram() +
      ggtitle(title_example) +
      theme(plot.title = element_textbox_simple())
    #> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.