0

With code I plot a combined figure:

library(ggplot2)
library(tidyverse)
library(patchwork)
library(glue)
library(cowplot)

small <- mtcars %>% 
  filter(carb %in% c(1, 2))

p1 <- qplot(mpg, wt, data = small, colour = cyl)
p2 <- qplot(mpg, data = small) + ggtitle("small")
p <- p1 | p2

n1 = 3
s1 = 'Zinc, Nickel, Silver'
n2 = 2
s2 = 'Copper, Aluminum'

text <- glue("The top {n1} commodities that price rose most are: {s1}; \\
    the top {n2} commodities that fell most are: {s2}.")
title <- ggdraw() + 
  draw_label(text, size=12)

plot_grid(title, p, ncol=1, rel_heights=c(0.1, 1))

Out:

enter image description here

Now the problem is explanation text on the top could not adaptively start a newline to show all the content? Let's say if text is a long paragraph, it will exceed out of plot bound.

How could I solve this issue? Thanks for your comments and helps at advance.

ah bon
  • 9,293
  • 12
  • 65
  • 148

1 Answers1

3
  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))
    
Jon Spring
  • 55,165
  • 4
  • 35
  • 53