rplottexttiffgeom-text

How to plot text only, without any margin, in a tiff file?


I want to build a tiff file with text only and no margins around the text, using R.

I tried :

library(ggplot2)

plt <- ggplot() +
  geom_text(aes(x=0,y=0,label="test")) +
  theme_void()

ggsave(plt,filename="test.tif",bg="transparent")

However, there are large margins (I have added the borderline to highlight these margins):

enter image description here

What I want to get is a file with the image of the text, without any margin: enter image description here

Is there a way to create such a tiff file, using ggplot, plot or any other R function?


Solution

  • This is pretty close, in base R: thanks to @r2evans for code to auto-adjust the width/height of the image:

    txt <- "hello world"
    dev.new()
    tiff("test.tiff", strwidth(txt, units="in"), 
           strheight(txt, units="in"), units="in", res=300)
    par(mar = rep(0,4))
    plot(0:1, 0:1, type = "n", ann = FALSE, axes=FALSE)
    text(0.5, 0.5, txt)
    dev.off()
    

    "hello world"