How to create a textbox-like object without plot

195 views Asked by At

I'm creating some R scripts. In one of them, I would like to write formatted text enclosed in a box to a png. I don't know how many lines of text there are, or what the length of the longest line is until I get into the R script, but I want to keep the formatting of the line and have the text fairly tightly enclosed. When I use a plot and a textbox, the plot comes with a large amount of graphical baggage and undesired behavior.

Is there anything that displays text on the device area that

  • does not require a plot,
  • wraps lines if they exceed a desired width, and
  • tightly surrounds the final text with a box?
1

There are 1 answers

4
zephryl On BEST ANSWER

You can use ggtext::geom_textbox() in conjunction with theme_void():

library(ggplot2)
library(ggtext)

txt <- "All human beings are born free and equal in dignity and rights. They are endowed with reason and conscience and should act towards one another in a spirit of brotherhood."

ggplot() +
  geom_textbox(
    aes(x = 0, y = 0, label = txt),
    size = 18 / .pt,
    width = unit(6, "inches")
  ) + 
  theme_void() 

You’ll likely need to play with font size, box size, and plot size.