1

我正在使用{glue}包来编写表达式,然后我将其解析并显示在 ggplot2 注释中。

但是,如果我有一个多行表达式,它们不会垂直对齐。我怎样才能实现这样的对齐?我以为atop + displaystyle会这样做,但事实并非如此。

library(ggplot2)
library(glue)

b.text <- "bottom part of the expression"
t.text <- "top part of the expression"

ggplot() +
  labs(subtitle = parse(text = glue("list(atop('{t.text}', '{b.text}'))")))

4

2 回答 2

2

我建议创建一个向量并使用glue_collapse 用换行符折叠它

library(ggplot2)
library(glue)

b.text <- "bottom part of the expression"
t.text <- "top part of the expression"
vec <- c(t.text, b.text)

ggplot() +
  labs(subtitle = glue_collapse(vec, sep = "\n"))

reprex 包于 2021-11-25 创建(v2.0.1)

于 2021-11-25T16:45:31.687 回答
1

如果我们想使用 OP 的代码,在字符串中用更少的字符填充空格

library(ggplot2)
library(stringr)
library(glue)
mx <- max(nchar(t.text), nchar(b.text)) + 1
ggplot() +
   labs(subtitle = parse(text = glue("list(atop('{str_pad(t.text, width = mx + 2, side = 'right')}', '{b.text}'))")))
于 2021-11-25T17:00:35.567 回答