How to use bold font combined with plain font and line breaks in ggplot2?

Viewed 222

In a plot made with the ggplot2 package I want to put a subtitle with a part of the text in bold and the other in plain fonts. Also, I would like to make 2 lines of text.

So far I've been trying with the expression() and bold() functions, and the \n; but I can't get the expected result:

Item 1: Text

Item 2: Text

library(ggplot2)

ggplot(data = mpg,
       aes(x = cyl,
           y = year)) +
  geom_point() +
  labs(subtitle = expression(bold("Item 1:")*" Text\n"*bold("Item 2:")*" Text"))

enter image description here

1 Answers

As suggested by @p0bs in his comment one option to achieve your desired result would be to make use of the ggtext package which allows to style text via markdown and/or HTML/CSS, e.g. to switch to bold fontface wrap text inside **, to add a line break use the HTML tag <br>:

library(ggplot2)
library(ggtext)

ggplot(data = mpg, aes(x = cyl, y = year)) +
  geom_point() +
  labs(subtitle = "**Item 1:** Text<br>**Item 2:** Text") +
  theme(plot.subtitle = ggtext::element_markdown())

Related