0

使用代码,我绘制了一个组合图:

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))

出去:

在此处输入图像描述

现在的问题是顶部的解释文本无法自适应地开始换行以显示所有内容?假设文本是一个长段落,它将超出情节界限。

我该如何解决这个问题?感谢您的评论和提前帮助。

4

1 回答 1

3
  1. 不精确但简单的选项。这只是根据字符数进行换行,而不考虑字体大小、特定字母宽度等。

    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. 更多控制选项。这用于ggtext::geom_textbox定义具有特定宽度、反映字体和特定字符的文本框。如果您想对标题中的某些文本进行着色或加粗,还可以包括更多选项。

    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))
    
于 2022-01-12T05:12:38.323 回答