0

I am trying to use the bold() and underline() functions from grDevices within paste() to create an annotation that features a stylized, hardcoded 'title' with a line break followed by a string that could be one or more lines long, and am struggling to accomplish it. (This is being done within a ShinyApp, so I can't hardcode two adjacent annotations because the number of lines within the string will vary based on user inputs.)

library(ggplot2)
library(grDevices)

mydata <- data.frame(Strings = c("This is a list of strings", 
                                 "They could be \n one line long",
                                 "Or they could \n be several lines \n long"),
                     NumberOfLines = c(1, 2, 3))

rowposition <- sample(1:3, 1)

mystring <- mydata$Strings[rowposition]

emptydataframe <- data.frame()

ggplot(emptydataframe) +
  geom_blank() +
  annotate("text", x = 8, y = -4,
           label = paste(bold(underline("Title\n")), mystring),
           size = 3)

The plot that is returned contains "Title" wrapped in alphanumeric gibberish followed by the string.

Any help is much appreciated.

Claus Wilke
  • 16,992
  • 7
  • 53
  • 104
Bryce R.
  • 11
  • 3

1 Answers1

3

Using the ggtext package:

library(ggtext)
ggplot(emptydataframe) +
  geom_blank() +
  annotate("richtext", x = 8, y = -4,
           label = paste("<b>Title</b><br>", mystring),
           size = 3)

enter image description here

Phil
  • 7,287
  • 3
  • 36
  • 66
  • 1
    It can't underline, though. Probably for the better. Underlining is a relic from the typewriter days and should generally be avoided. – Claus Wilke Sep 18 '20 at 22:48