5

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.stack.imgur.com/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!

Francesca
  • 73
  • 1
  • 6
  • Is this an option? https://stackoverflow.com/q/33484458/36061 – masher Feb 08 '21 at 16:21
  • Thanks @masher for noticing this related question! Since it´s rather a workaround I´ll use the package `ggtext` as suggested by @teunbrand which works great! – Francesca Feb 10 '21 at 16:33

1 Answers1

11

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

teunbrand
  • 33,645
  • 4
  • 37
  • 63
  • This works perfect for me, thanks @teunbrand! If someone is wondering how to center your title `plot.title = element_textbox_simple(halign = 0.5)` does the trick – Francesca Feb 10 '21 at 16:33