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:
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.
CodePudding user response:
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)More control option. This uses
ggtext::geom_textboxto 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))

