I can create a shadow-text in an empty ggplot2 plot as described here. I want to create a huge number of such plots, where:
- the text size is automatically adjusted in case the text is too long to fit the width of the empty plot
- the text is automatically centered in the middle of the empty plot
Consider the following example:
library("ggrepel") # Load packages
library("ggplot2")
my_text <- c("Text 1", # Three different text elements
"Loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong Text 2",
"Some Other Text 3")
for(i in 1:length(my_text)) {
ggp <- ggplot() + # Draw ggplot2 plot with text only
theme_void() +
geom_text_repel(mapping = aes(1, 1, label = my_text[i]),
color = "blue",
bg.color = "red",
bg.r = 0.05)
ggsave(ggp, # Save ggplot2 plot
filename = paste0("my_text_", i, ".png"),
bg = "transparent",
width = 101.6,
height = 57.15,
scale = 0.05,
dpi = 1000)
}
The output of the previous R code looks as follows:
As you can see, we have created three different images with shadow-text. However, none of these text elements is aligned exactly in the middle of the plot. Furthermore, the second text is too long to fit the plotting area and should therefore have a smaller font size.
How could I automatically adjust the font size if necessary, and how could I automatically center each text?