Home > Software design >  aligning multi-line `glue` expression
aligning multi-line `glue` expression

Time:11-26

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

CodePudding user response:

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)

CodePudding user response:

If we want to use the OP's code, pad space in the string with less number of characters

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