Search code examples
rggplot2r-glue

aligning multi-line `glue` expression


I am using {glue} package to write expressions, which I then parse and display in ggplot2 annotations.

But, if I have a multiline expression, they are not vertically aligned. How can I achieve such an alignment? I thought atop + displaystyle would do this, but it doesn't.

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}'))")))


Solution

  • I'd suggest to create a vector and use glue_collapse to collapse it with a linebreak

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

    Created on 2021-11-25 by the reprex package (v2.0.1)