Skip to content
R for the Rest of Us Logo

How to wrap text automatically in ggplot

If you've ever spent time in ggplot trying to get the width of text elements just right, this tip is for you! I recently learned from Nicola Rennie about the element_textbox_simple() function from the ggtext package. This function will automatically wrap your title, subtitle, or other text so that it fits perfectly with your plot.

Code shown in video

library(tidyverse)
library(palmerpenguins)

penguins |>
  count(island) |>
  ggplot(
    aes(
      x = island,
      y = n
    )
  ) +
  geom_col() +
  labs(
    title = "Biscoe island has the most penguins",
    subtitle = "But the other islands are still great. There are penguins living there. So hey, don't ignore those two islands, ok?"
  )

penguins |>
  count(island) |>
  ggplot(
    aes(
      x = island,
      y = n
    )
  ) +
  geom_col() +
  labs(
    title = "Biscoe island has the most penguins",
    subtitle = str_wrap("But the other islands are still great. There are penguins living there. So hey, don't ignore those two islands, ok?", width = 10)
  )

library(tidyverse)
library(palmerpenguins)
library(ggtext)

penguins |>
  count(island) |>
  ggplot(
    aes(
      x = island,
      y = n
    )
  ) +
  geom_col() +
  labs(
    title = "Biscoe island has the most penguins",
    subtitle = "But the other islands are still great. There are penguins living there. So hey, don't ignore those two islands, ok?"
  ) +
  theme(
    plot.subtitle = element_textbox_simple()
  )

Sign up for the newsletter

Get blog posts like this delivered straight to your inbox.

Let us know what you think by adding a comment below.

You need to be signed-in to comment on this post. Login.

David Keyes
By David Keyes
August 15, 2024

Sign up for the newsletter

R tips and tricks straight to your inbox.