Adaptively start a newline for ggplot text (title, subtitle, caption, etc.) using R

Solution 1:

  1. Imprecise but simple option. This just wraps based on count of characters, regardless of font size, specific letter widths, etc.

    text <- stringr::str_wrap(glue("The top {n1} commodities that price rose most are: {s1}; \\
                        the top {n2} commodities that fell most are: {s2}."), 80)
    
  2. More control option. This uses ggtext::geom_textbox to define a textbox with specific width, reflecting font and specific characters. Could also include further options if you want to color or bold certain text within the title.

    ggplot() +
       ggtext::geom_textbox(data = tibble(label = text), 
                           width = unit(5, "inch"), box.colour = NA,
                           aes(label = label, x = 1, y = 1)) +
      theme_void() -> t
    
    t / p + plot_layout(heights = c(1,5))