How do I bold and underline part of a ggplot2 annotation?

1k Views Asked by At

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.

1

There are 1 best solutions below

1
On

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