1

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

Indrajeet Patil
  • 4,673
  • 2
  • 20
  • 51

2 Answers2

2

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)

Seb
  • 332
  • 1
  • 3
1

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}'))")))
akrun
  • 874,273
  • 37
  • 540
  • 662