使用 R 自适应地为 ggplot 文本(标题、副标题、标题等)开始换行
Adaptively start a newline for ggplot text (title, subtitle, caption, etc.) using R
我用代码绘制了一个组合图:
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))
输出:
现在的问题是顶部的解释文字无法自适应地开始换行显示所有内容?比方说,如果文本是一个长段落,它将超出绘图范围。
我该如何解决这个问题?提前感谢您的意见和帮助。
不精确但简单的选项。这只是根据字符数换行,而不考虑字体大小、特定字母宽度等。
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)
更多控制选项。这使用 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))
我用代码绘制了一个组合图:
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))
输出:
现在的问题是顶部的解释文字无法自适应地开始换行显示所有内容?比方说,如果文本是一个长段落,它将超出绘图范围。
我该如何解决这个问题?提前感谢您的意见和帮助。
不精确但简单的选项。这只是根据字符数换行,而不考虑字体大小、特定字母宽度等。
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)
更多控制选项。这使用
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))