【问题标题】:aligning multi-line `glue` expression对齐多行“胶水”表达式
【发布时间】:2022-01-03 22:25:15
【问题描述】:

我正在使用{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}'))")))

【问题讨论】:

    标签: r ggplot2 r-glue


    【解决方案1】:

    我建议创建一个向量并使用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 package (v2.0.1) 于 2021 年 11 月 25 日创建

    【讨论】:

      【解决方案2】:

      如果我们想使用 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}'))")))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-12-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-10-05
        • 2022-01-20
        • 1970-01-01
        相关资源
        最近更新 更多