"

How to add space around the title of a ggplot the better way

👉The margin argument from 📦{ggtext}’s element_markdown()
Author
Affiliation

Building Stories with Data

Published

June 10, 2022

No more <br><br>My title<br>! (although does achieve a margin which is nicely related to the text size - silver linings)

R code snippet demonstrating two methods for adjusting title and subtitle spacing in ggplot2. The first uses basic line breaks, while the second offers more control with `element_markdown` and `unit` for precise margin settings.

library(ggtext)

# The "this will work for now" approach
plot +
  labs(
    title = "<br>This title needs a bit more space",
    subtitle = "<br>And so does the subtitle!<br>"
  ) +
  theme(plot.title = element_markdown(), plot.subtitle = element_markdown())


# The approach that gives you a lot more control about
# how much space you add around both the title
# and the subtitle!
plot +
  labs(
    title = "This title needs a bit more space",
    subtitle = "And so does the subtitle!"
  ) +
  # margin is specified with the order: top, right, bottom, left
  theme(
    plot.title = element_markdown(margin = unit(c(1, 0, 0.5, 0), "cm")),
    plot.subtitle = element_markdown(margin = unit(c(0, 0, 0.5, 0), "cm"))
  )

P.S. At the time of republishing this, {marquee} is taking off - in which the margins work in exactly the same way. Happy days!

Reuse

Citation

For attribution, please cite this work as:
Thompson, Cara. 2022. “How to Add Space Around the Title of a Ggplot the Better Way.” June 10, 2022. https://www.cararthompson.com/posts/2022-06-10-todays-i-wish-id-looked/.