簡體   English   中英

使用 R 自適應地為 ggplot 文本(標題、副標題、標題等)開始換行

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

與代碼 I plot 組合圖:

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

出去:

在此處輸入圖像描述

現在的問題是頂部的解釋文本無法自適應地開始換行以顯示所有內容? 假設文本是長段落,它將超出 plot 界限。

我該如何解決這個問題? 感謝您的評論和提前幫助。

  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() -> tt / p + plot_layout(heights = c(1,5))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM